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
FStar.Stubs.Tactics.Types.fsti
FStar.Stubs.Tactics.Types.issues
val issues : Type0
let issues = list FStar.Issue.issue
{ "file_name": "ulib/FStar.Stubs.Tactics.Types.fsti", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 35, "end_line": 71, "start_col": 0, "start_line": 71 }
(* Copyright 2008-2018 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 FStar.Stubs.Tactics.Types open FStar.Stubs.Reflection.Types include FStar.Stubs.Tactics.Common include FStar.Stubs.TypeChecker.Core assume new type goal assume new type proofstate (* Returns the active goals *) val goals_of : proofstate -> list goal (* Returns the goals marked for SMT *) val smt_goals_of : proofstate -> list goal (* Inspecting a goal *) val goal_env : goal -> env val goal_type : goal -> typ val goal_witness : goal -> term val is_guard : goal -> bool (* A bit of helper info: did this goal come from a VC guard? *) val get_label : goal -> string val set_label : string -> goal -> goal (* Tracing *) val incr_depth : proofstate -> proofstate val decr_depth : proofstate -> proofstate (* [tracepoint] always returns true. We do not use unit to prevent erasure. *) val tracepoint : proofstate -> b:bool{b == true} val set_proofstate_range : proofstate -> FStar.Range.range -> proofstate type direction = | TopDown | BottomUp type ctrl_flag = | Continue | Skip | Abort type guard_policy = | Goal // Add guards as (normal) goals | SMT // Add guards as SMT goals | SMTSync // Send guards to SMT immediately, will *log* errors (not raise) if anything fails | Force // Force guards without SMT | Drop // Drop guards, clearly unsound! careful! (* Typing reflection *) val non_informative_token (g:env) (t:typ) : Type0 val subtyping_token (g:env) (t0 t1:typ) : Type0 val equiv_token (g:env) (t0 t1:typ) : Type0 val typing_token (g:env) (e:term) (c:tot_or_ghost & typ) : Type0 (* Must be inline, this definition is not there in src/FStar.Tactics.Types *)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Stubs.TypeChecker.Core.fsti.checked", "FStar.Stubs.Tactics.Common.fsti.checked", "FStar.Stubs.Reflection.Types.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.fsti.checked", "FStar.Issue.fsti.checked" ], "interface_file": false, "source_file": "FStar.Stubs.Tactics.Types.fsti" }
[ { "abbrev": false, "full_module": "FStar.Stubs.TypeChecker.Core", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics.Common", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Reflection.Types", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Stubs.Tactics", "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
Type0
Prims.Tot
[ "total" ]
[]
[ "Prims.list", "FStar.Issue.issue" ]
[]
false
false
false
true
true
let issues =
list FStar.Issue.issue
false
Vale.Inline.X64.Fadd_inline.fsti
Vale.Inline.X64.Fadd_inline.u1024
val u1024 : Type0
let u1024 = b:B.buffer UInt64.t{B.length b == 16}
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 49, "end_line": 15, "start_col": 0, "start_line": 15 }
module Vale.Inline.X64.Fadd_inline open Vale.X64.CPU_Features_s open FStar.HyperStack.ST module B = LowStar.Buffer module HS = FStar.HyperStack open Vale.Curve25519.Fast_defs open FStar.Mul unfold let u256 = b:B.buffer UInt64.t{B.length b == 4} unfold let u512 = b:B.buffer UInt64.t{B.length b == 8}
{ "checked_file": "/", "dependencies": [ "Vale.X64.CPU_Features_s.fst.checked", "Vale.Curve25519.Fast_defs.fst.checked", "prims.fst.checked", "LowStar.Buffer.fst.checked", "FStar.UInt64.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Vale.Inline.X64.Fadd_inline.fsti" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Vale.Curve25519.Fast_defs", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.X64.CPU_Features_s", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Type0
Prims.Tot
[ "total" ]
[]
[ "LowStar.Buffer.buffer", "FStar.UInt64.t", "Prims.eq2", "Prims.int", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder" ]
[]
false
false
false
true
true
let u1024 =
b: B.buffer UInt64.t {B.length b == 16}
false
Vale.Inline.X64.Fadd_inline.fsti
Vale.Inline.X64.Fadd_inline.u256
val u256 : Type0
let u256 = b:B.buffer UInt64.t{B.length b == 4}
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 47, "end_line": 11, "start_col": 0, "start_line": 11 }
module Vale.Inline.X64.Fadd_inline open Vale.X64.CPU_Features_s open FStar.HyperStack.ST module B = LowStar.Buffer module HS = FStar.HyperStack open Vale.Curve25519.Fast_defs open FStar.Mul
{ "checked_file": "/", "dependencies": [ "Vale.X64.CPU_Features_s.fst.checked", "Vale.Curve25519.Fast_defs.fst.checked", "prims.fst.checked", "LowStar.Buffer.fst.checked", "FStar.UInt64.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Vale.Inline.X64.Fadd_inline.fsti" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Vale.Curve25519.Fast_defs", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.X64.CPU_Features_s", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Type0
Prims.Tot
[ "total" ]
[]
[ "LowStar.Buffer.buffer", "FStar.UInt64.t", "Prims.eq2", "Prims.int", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder" ]
[]
false
false
false
true
true
let u256 =
b: B.buffer UInt64.t {B.length b == 4}
false
Vale.Inline.X64.Fadd_inline.fsti
Vale.Inline.X64.Fadd_inline.u512
val u512 : Type0
let u512 = b:B.buffer UInt64.t{B.length b == 8}
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 47, "end_line": 13, "start_col": 0, "start_line": 13 }
module Vale.Inline.X64.Fadd_inline open Vale.X64.CPU_Features_s open FStar.HyperStack.ST module B = LowStar.Buffer module HS = FStar.HyperStack open Vale.Curve25519.Fast_defs open FStar.Mul unfold let u256 = b:B.buffer UInt64.t{B.length b == 4}
{ "checked_file": "/", "dependencies": [ "Vale.X64.CPU_Features_s.fst.checked", "Vale.Curve25519.Fast_defs.fst.checked", "prims.fst.checked", "LowStar.Buffer.fst.checked", "FStar.UInt64.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Vale.Inline.X64.Fadd_inline.fsti" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Vale.Curve25519.Fast_defs", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.X64.CPU_Features_s", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Type0
Prims.Tot
[ "total" ]
[]
[ "LowStar.Buffer.buffer", "FStar.UInt64.t", "Prims.eq2", "Prims.int", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder" ]
[]
false
false
false
true
true
let u512 =
b: B.buffer UInt64.t {B.length b == 8}
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_st_sub
val elab_st_sub (#g: env) (#c1 #c2: comp) (d_sub: st_sub g c1 c2) : Tot (t: R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2)))
val elab_st_sub (#g: env) (#c1 #c2: comp) (d_sub: st_sub g c1 c2) : Tot (t: R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2)))
let elab_st_sub (#g:env) (#c1 #c2 : comp) (d_sub : st_sub g c1 c2) : Tot (t:R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2))) = RU.magic_s "elab_st_sub"
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 26, "end_line": 161, "start_col": 0, "start_line": 157 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term) : Tot R.term = match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e let intro_pure_tm (p:term) = let open Pulse.Reflection.Util in wtag (Some STT_Ghost) (Tm_STApp { head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p; arg_qual = None; arg = tm_fstar (`()) Range.range_0 }) let simple_arr (t1 t2 : R.term) : R.term = let b = R.pack_binder { sort = t1; ppname = Sealed.seal "x"; qual = R.Q_Explicit; attrs = [] } in R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
d_sub: Pulse.Typing.st_sub g c1 c2 -> Prims.dtuple2 FStar.Stubs.Reflection.Types.term (fun t -> FStar.Reflection.Typing.tot_typing (Pulse.Typing.elab_env g) t (Pulse.Elaborate.Core.simple_arr (Pulse.Elaborate.Pure.elab_comp c1) (Pulse.Elaborate.Pure.elab_comp c2)))
Prims.Tot
[ "total" ]
[]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.comp", "Pulse.Typing.st_sub", "Pulse.RuntimeUtils.magic_s", "Prims.dtuple2", "FStar.Stubs.Reflection.Types.term", "FStar.Reflection.Typing.tot_typing", "Pulse.Typing.elab_env", "Pulse.Elaborate.Core.simple_arr", "Pulse.Elaborate.Pure.elab_comp" ]
[]
false
false
false
false
false
let elab_st_sub (#g: env) (#c1 #c2: comp) (d_sub: st_sub g c1 c2) : Tot (t: R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2))) =
RU.magic_s "elab_st_sub"
false
Pulse.Checker.IntroPure.fst
Pulse.Checker.IntroPure.check_prop_validity
val check_prop_validity (g: env) (p: term) (typing: tot_typing g p tm_prop) : T.Tac (prop_validity g p)
val check_prop_validity (g: env) (p: term) (typing: tot_typing g p tm_prop) : T.Tac (prop_validity g p)
let check_prop_validity (g:env) (p:term) (typing:tot_typing g p tm_prop): T.Tac (prop_validity g p) = Pulse.Checker.Pure.check_prop_validity g p typing
{ "file_name": "lib/steel/pulse/Pulse.Checker.IntroPure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 53, "end_line": 44, "start_col": 0, "start_line": 43 }
(* Copyright 2023 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 Pulse.Checker.IntroPure open Pulse.Syntax open Pulse.Typing open Pulse.Checker.Base open Pulse.Checker.Prover module T = FStar.Tactics.V2 module P = Pulse.Syntax.Printer let check_prop (g:env) (p:term) : T.Tac (p:term & tot_typing g p tm_prop) = let p0 = p in let (| p, p_typing |) = Pulse.Checker.Pure.check_vprop g (tm_pure p) in match p.t with | Tm_Pure pp -> let prop_typing = Pulse.Typing.Metatheory.pure_typing_inversion #_ #pp p_typing in (| pp, prop_typing |) | _ -> fail g None (Printf.sprintf "Impossible: check_intro_pure: checking a pure vprop %s returned a non-pure vprop %s,\ please file a bug-report" (P.term_to_string (tm_pure p0)) (P.term_to_string p))
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.Metatheory.fsti.checked", "Pulse.Typing.Env.fsti.checked", "Pulse.Typing.fst.checked", "Pulse.Syntax.Printer.fsti.checked", "Pulse.Syntax.fst.checked", "Pulse.Checker.Pure.fsti.checked", "Pulse.Checker.Prover.fsti.checked", "Pulse.Checker.Base.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": true, "source_file": "Pulse.Checker.IntroPure.fst" }
[ { "abbrev": true, "full_module": "Pulse.Syntax.Printer", "short_module": "P" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "Pulse.Checker.Prover", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker.Base", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "Pulse.Checker.Base", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker", "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: Pulse.Typing.Env.env -> p: Pulse.Syntax.Base.term -> typing: Pulse.Typing.tot_typing g p Pulse.Typing.tm_prop -> FStar.Tactics.Effect.Tac (Pulse.Typing.prop_validity g p)
FStar.Tactics.Effect.Tac
[]
[]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.term", "Pulse.Typing.tot_typing", "Pulse.Typing.tm_prop", "Pulse.Checker.Pure.check_prop_validity", "Pulse.Typing.prop_validity" ]
[]
false
true
false
false
false
let check_prop_validity (g: env) (p: term) (typing: tot_typing g p tm_prop) : T.Tac (prop_validity g p) =
Pulse.Checker.Pure.check_prop_validity g p typing
false
Vale.Inline.X64.Fadd_inline.fsti
Vale.Inline.X64.Fadd_inline.as_nat
val as_nat (b: B.buffer UInt64.t {B.length b == 4}) (h: HS.mem) : GTot nat
val as_nat (b: B.buffer UInt64.t {B.length b == 4}) (h: HS.mem) : GTot nat
let as_nat (b:B.buffer UInt64.t{B.length b == 4}) (h:HS.mem) : GTot nat = let s = B.as_seq h b in let s0 = UInt64.v (Seq.index s 0) in let s1 = UInt64.v (Seq.index s 1) in let s2 = UInt64.v (Seq.index s 2) in let s3 = UInt64.v (Seq.index s 3) in pow2_four s0 s1 s2 s3
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 23, "end_line": 23, "start_col": 0, "start_line": 17 }
module Vale.Inline.X64.Fadd_inline open Vale.X64.CPU_Features_s open FStar.HyperStack.ST module B = LowStar.Buffer module HS = FStar.HyperStack open Vale.Curve25519.Fast_defs open FStar.Mul unfold let u256 = b:B.buffer UInt64.t{B.length b == 4} unfold let u512 = b:B.buffer UInt64.t{B.length b == 8} unfold let u1024 = b:B.buffer UInt64.t{B.length b == 16}
{ "checked_file": "/", "dependencies": [ "Vale.X64.CPU_Features_s.fst.checked", "Vale.Curve25519.Fast_defs.fst.checked", "prims.fst.checked", "LowStar.Buffer.fst.checked", "FStar.UInt64.fsti.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked", "FStar.Ghost.fsti.checked" ], "interface_file": false, "source_file": "Vale.Inline.X64.Fadd_inline.fsti" }
[ { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Vale.Curve25519.Fast_defs", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.X64.CPU_Features_s", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Inline.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
b: LowStar.Buffer.buffer FStar.UInt64.t {LowStar.Monotonic.Buffer.length b == 4} -> h: FStar.Monotonic.HyperStack.mem -> Prims.GTot Prims.nat
Prims.GTot
[ "sometrivial" ]
[]
[ "LowStar.Buffer.buffer", "FStar.UInt64.t", "Prims.eq2", "Prims.int", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder", "FStar.Monotonic.HyperStack.mem", "Vale.Curve25519.Fast_defs.pow2_four", "FStar.UInt.uint_t", "FStar.UInt64.v", "FStar.Seq.Base.index", "FStar.Seq.Base.seq", "LowStar.Monotonic.Buffer.as_seq", "Prims.nat" ]
[]
false
false
false
false
false
let as_nat (b: B.buffer UInt64.t {B.length b == 4}) (h: HS.mem) : GTot nat =
let s = B.as_seq h b in let s0 = UInt64.v (Seq.index s 0) in let s1 = UInt64.v (Seq.index s 1) in let s2 = UInt64.v (Seq.index s 2) in let s3 = UInt64.v (Seq.index s 3) in pow2_four s0 s1 s2 s3
false
Vale.Stdcalls.X64.Aes.fst
Vale.Stdcalls.X64.Aes.aes128_key_expansion
val aes128_key_expansion : normal lowstar_key128_t
val aes128_key_expansion : normal lowstar_key128_t
let aes128_key_expansion //: normal lowstar_key128_t = as_normal_t #lowstar_key128_t lowstar_key128
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 48, "end_line": 31, "start_col": 0, "start_line": 30 }
module Vale.Stdcalls.X64.Aes open FStar.Mul open FStar.HyperStack.ST module HS = FStar.HyperStack module B = LowStar.Buffer module DV = LowStar.BufferView.Down module UV = LowStar.BufferView.Up open Vale.Def.Types_s open Vale.Interop.Base module IX64 = Vale.Interop.X64 module VSig = Vale.AsLowStar.ValeSig module LSig = Vale.AsLowStar.LowStarSig module ME = Vale.X64.Memory module V = Vale.X64.Decls module IA = Vale.Interop.Assumptions module W = Vale.AsLowStar.Wrapper open Vale.X64.MemoryAdapters module VS = Vale.X64.State module MS = Vale.X64.Machine_s let lowstar_key128 : lowstar_key128_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 4); IX64.wrap_weak_stdcall code_key128 dom (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win))
{ "checked_file": "/", "dependencies": [ "Vale.X64.State.fsti.checked", "Vale.X64.MemoryAdapters.fsti.checked", "Vale.X64.Memory.fsti.checked", "Vale.X64.Machine_s.fst.checked", "Vale.X64.Decls.fsti.checked", "Vale.Interop.X64.fsti.checked", "Vale.Interop.Base.fst.checked", "Vale.Interop.Assumptions.fst.checked", "Vale.Def.Types_s.fst.checked", "Vale.AsLowStar.Wrapper.fsti.checked", "Vale.AsLowStar.ValeSig.fst.checked", "Vale.AsLowStar.LowStarSig.fst.checked", "prims.fst.checked", "LowStar.BufferView.Up.fsti.checked", "LowStar.BufferView.Down.fsti.checked", "LowStar.Buffer.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.List.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked" ], "interface_file": true, "source_file": "Vale.Stdcalls.X64.Aes.fst" }
[ { "abbrev": true, "full_module": "Vale.AES.X64.AES", "short_module": "AE" }, { "abbrev": false, "full_module": "Vale.AES.AES_s", "short_module": null }, { "abbrev": true, "full_module": "Vale.X64.Machine_s", "short_module": "MS" }, { "abbrev": true, "full_module": "Vale.X64.State", "short_module": "VS" }, { "abbrev": false, "full_module": "Vale.X64.MemoryAdapters", "short_module": null }, { "abbrev": true, "full_module": "Vale.AsLowStar.Wrapper", "short_module": "W" }, { "abbrev": true, "full_module": "Vale.Interop.Assumptions", "short_module": "IA" }, { "abbrev": true, "full_module": "Vale.X64.Decls", "short_module": "V" }, { "abbrev": true, "full_module": "Vale.X64.Memory", "short_module": "ME" }, { "abbrev": true, "full_module": "Vale.AsLowStar.LowStarSig", "short_module": "LSig" }, { "abbrev": true, "full_module": "Vale.AsLowStar.ValeSig", "short_module": "VSig" }, { "abbrev": true, "full_module": "Vale.Interop.X64", "short_module": "IX64" }, { "abbrev": false, "full_module": "Vale.Interop.Base", "short_module": null }, { "abbrev": false, "full_module": "Vale.Def.Types_s", "short_module": null }, { "abbrev": true, "full_module": "LowStar.BufferView.Up", "short_module": "UV" }, { "abbrev": true, "full_module": "LowStar.BufferView.Down", "short_module": "DV" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Vale.Interop.Base.normal Vale.Stdcalls.X64.Aes.lowstar_key128_t
Prims.Tot
[ "total" ]
[]
[ "Vale.Stdcalls.X64.Aes.as_normal_t", "Vale.Stdcalls.X64.Aes.lowstar_key128_t", "Vale.Stdcalls.X64.Aes.lowstar_key128" ]
[]
false
false
false
true
false
let aes128_key_expansion =
as_normal_t #lowstar_key128_t lowstar_key128
false
Vale.Stdcalls.X64.Aes.fst
Vale.Stdcalls.X64.Aes.aes256_key_expansion
val aes256_key_expansion : normal lowstar_key256_t
val aes256_key_expansion : normal lowstar_key256_t
let aes256_key_expansion //: normal lowstar_key256_t = as_normal_t #lowstar_key256_t lowstar_key256
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 48, "end_line": 41, "start_col": 0, "start_line": 40 }
module Vale.Stdcalls.X64.Aes open FStar.Mul open FStar.HyperStack.ST module HS = FStar.HyperStack module B = LowStar.Buffer module DV = LowStar.BufferView.Down module UV = LowStar.BufferView.Up open Vale.Def.Types_s open Vale.Interop.Base module IX64 = Vale.Interop.X64 module VSig = Vale.AsLowStar.ValeSig module LSig = Vale.AsLowStar.LowStarSig module ME = Vale.X64.Memory module V = Vale.X64.Decls module IA = Vale.Interop.Assumptions module W = Vale.AsLowStar.Wrapper open Vale.X64.MemoryAdapters module VS = Vale.X64.State module MS = Vale.X64.Machine_s let lowstar_key128 : lowstar_key128_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 4); IX64.wrap_weak_stdcall code_key128 dom (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win)) let aes128_key_expansion //: normal lowstar_key128_t = as_normal_t #lowstar_key128_t lowstar_key128 let lowstar_key256 : lowstar_key256_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 4); IX64.wrap_weak_stdcall code_key256 dom (W.mk_prediction code_key256 dom [] (key256_lemma code_key256 IA.win))
{ "checked_file": "/", "dependencies": [ "Vale.X64.State.fsti.checked", "Vale.X64.MemoryAdapters.fsti.checked", "Vale.X64.Memory.fsti.checked", "Vale.X64.Machine_s.fst.checked", "Vale.X64.Decls.fsti.checked", "Vale.Interop.X64.fsti.checked", "Vale.Interop.Base.fst.checked", "Vale.Interop.Assumptions.fst.checked", "Vale.Def.Types_s.fst.checked", "Vale.AsLowStar.Wrapper.fsti.checked", "Vale.AsLowStar.ValeSig.fst.checked", "Vale.AsLowStar.LowStarSig.fst.checked", "prims.fst.checked", "LowStar.BufferView.Up.fsti.checked", "LowStar.BufferView.Down.fsti.checked", "LowStar.Buffer.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.List.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked" ], "interface_file": true, "source_file": "Vale.Stdcalls.X64.Aes.fst" }
[ { "abbrev": true, "full_module": "Vale.AES.X64.AES", "short_module": "AE" }, { "abbrev": false, "full_module": "Vale.AES.AES_s", "short_module": null }, { "abbrev": true, "full_module": "Vale.X64.Machine_s", "short_module": "MS" }, { "abbrev": true, "full_module": "Vale.X64.State", "short_module": "VS" }, { "abbrev": false, "full_module": "Vale.X64.MemoryAdapters", "short_module": null }, { "abbrev": true, "full_module": "Vale.AsLowStar.Wrapper", "short_module": "W" }, { "abbrev": true, "full_module": "Vale.Interop.Assumptions", "short_module": "IA" }, { "abbrev": true, "full_module": "Vale.X64.Decls", "short_module": "V" }, { "abbrev": true, "full_module": "Vale.X64.Memory", "short_module": "ME" }, { "abbrev": true, "full_module": "Vale.AsLowStar.LowStarSig", "short_module": "LSig" }, { "abbrev": true, "full_module": "Vale.AsLowStar.ValeSig", "short_module": "VSig" }, { "abbrev": true, "full_module": "Vale.Interop.X64", "short_module": "IX64" }, { "abbrev": false, "full_module": "Vale.Interop.Base", "short_module": null }, { "abbrev": false, "full_module": "Vale.Def.Types_s", "short_module": null }, { "abbrev": true, "full_module": "LowStar.BufferView.Up", "short_module": "UV" }, { "abbrev": true, "full_module": "LowStar.BufferView.Down", "short_module": "DV" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Vale.Interop.Base.normal Vale.Stdcalls.X64.Aes.lowstar_key256_t
Prims.Tot
[ "total" ]
[]
[ "Vale.Stdcalls.X64.Aes.as_normal_t", "Vale.Stdcalls.X64.Aes.lowstar_key256_t", "Vale.Stdcalls.X64.Aes.lowstar_key256" ]
[]
false
false
false
true
false
let aes256_key_expansion =
as_normal_t #lowstar_key256_t lowstar_key256
false
IfcRulesReify.fst
IfcRulesReify.op_Less
val op_Less : label -> label -> Tot bool
val op_Less : label -> label -> Tot bool
let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 17, "end_line": 36, "start_col": 0, "start_line": 33 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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: IfcRulesReify.label -> l2: IfcRulesReify.label -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label", "FStar.Pervasives.Native.Mktuple2", "Prims.bool" ]
[]
false
false
false
true
false
let ( < ) l1 l2 =
match l1, l2 with | Low, High -> true | _, _ -> false
false
IfcRulesReify.fst
IfcRulesReify.op_Less_Equals
val op_Less_Equals : label -> label -> Tot bool
val op_Less_Equals : label -> label -> Tot bool
let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 16, "end_line": 42, "start_col": 0, "start_line": 39 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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: IfcRulesReify.label -> l2: IfcRulesReify.label -> Prims.bool
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label", "FStar.Pervasives.Native.Mktuple2", "Prims.bool" ]
[]
false
false
false
true
false
let ( <= ) l1 l2 =
match l1, l2 with | High, Low -> false | _, _ -> true
false
IfcRulesReify.fst
IfcRulesReify.ni_exp
val ni_exp (env: label_fun) (e: exp) (l: label) : Tot Type0
val ni_exp (env: label_fun) (e: exp) (l: label) : Tot Type0
let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 8, "end_line": 80, "start_col": 0, "start_line": 72 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> l: IfcRulesReify.label -> Type0
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "IfcRulesReify.label", "Prims.l_Forall", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "Prims.l_imp", "Prims.l_and", "IfcRulesReify.low_equiv", "Prims.b2t", "IfcRulesReify.uu___is_Low", "Prims.op_Equality", "Prims.int", "WhileReify.interpret_exp_st", "Rel.__proj__R__item__l", "Rel.__proj__R__item__r" ]
[]
false
false
false
true
true
let ni_exp (env: label_fun) (e: exp) (l: label) : Tot Type0 =
forall (h: rel heap). (low_equiv env h /\ Low? l) ==> (let vr = reify (interpret_exp_st e) (R?.r h) in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl)
false
IfcRulesReify.fst
IfcRulesReify.join
val join : label -> label -> Tot label
val join : label -> label -> Tot label
let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 16, "end_line": 48, "start_col": 0, "start_line": 45 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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: IfcRulesReify.label -> l2: IfcRulesReify.label -> IfcRulesReify.label
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label", "FStar.Pervasives.Native.Mktuple2", "IfcRulesReify.Low", "IfcRulesReify.High" ]
[]
false
false
false
true
false
let join l1 l2 =
match l1, l2 with | Low, Low -> Low | _, _ -> High
false
IfcRulesReify.fst
IfcRulesReify.meet
val meet : label -> label -> Tot label
val meet : label -> label -> Tot label
let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 15, "end_line": 54, "start_col": 0, "start_line": 51 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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: IfcRulesReify.label -> l2: IfcRulesReify.label -> IfcRulesReify.label
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label", "FStar.Pervasives.Native.Mktuple2", "IfcRulesReify.High", "IfcRulesReify.Low" ]
[]
false
false
false
true
false
let meet l1 l2 =
match l1, l2 with | High, High -> High | _, _ -> Low
false
IfcRulesReify.fst
IfcRulesReify.ni_com'
val ni_com' (env: label_fun) (c: com) (l: label) (h0: rel heap) : Tot Type0
val ni_com' (env: label_fun) (c: com) (l: label) (h0: rel heap) : Tot Type0
let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 5, "end_line": 110, "start_col": 0, "start_line": 96 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> c: WhileReify.com -> l: IfcRulesReify.label -> h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap -> Type0
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.com", "IfcRulesReify.label", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "WhileReify.interpret_com", "Prims.l_imp", "IfcRulesReify.low_equiv", "Rel.R", "FStar.Pervasives.Native.option", "Prims.l_True" ]
[]
false
false
false
true
true
let ni_com' (env: label_fun) (c: com) (l: label) (h0: rel heap) : Tot Type0 =
let R h0l h0r = h0 in match interpret_com h0l c with | Some h1l -> (match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True) | _ -> True
false
IfcRulesReify.fst
IfcRulesReify.ni_com
val ni_com (env: label_fun) (c: com) (l: label) : Tot Type0
val ni_com (env: label_fun) (c: com) (l: label) : Tot Type0
let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 87, "end_line": 114, "start_col": 0, "start_line": 112 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> c: WhileReify.com -> l: IfcRulesReify.label -> Type0
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.com", "IfcRulesReify.label", "Prims.l_and", "Prims.l_Forall", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "IfcRulesReify.ni_com'", "IfcRulesReify.inv_com'" ]
[]
false
false
false
true
true
let ni_com (env: label_fun) (c: com) (l: label) : Tot Type0 =
(forall (h0: rel heap). ni_com' env c l h0) /\ (forall (h0: heap). inv_com' env c l h0)
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_frame
val elab_frame : c: Pulse.Syntax.Base.comp_st -> frame: Pulse.Syntax.Base.term -> e: FStar.Stubs.Reflection.Types.term -> FStar.Stubs.Reflection.Types.term
let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 84, "end_line": 39, "start_col": 0, "start_line": 29 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
c: Pulse.Syntax.Base.comp_st -> frame: Pulse.Syntax.Base.term -> e: FStar.Stubs.Reflection.Types.term -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.comp_st", "Pulse.Syntax.Base.term", "FStar.Stubs.Reflection.Types.term", "Pulse.Syntax.Base.uu___is_C_ST", "Pulse.Reflection.Util.mk_frame_stt", "Pulse.Reflection.Util.mk_abs", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Elaborate.Pure.elab_term", "Prims.bool", "Pulse.Syntax.Base.uu___is_C_STAtomic", "Pulse.Reflection.Util.mk_frame_stt_atomic", "Pulse.Syntax.Base.comp_inames", "Pulse.Reflection.Util.mk_frame_stt_ghost", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.comp_pre", "Pulse.Syntax.Base.comp_res", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.comp_u" ]
[]
false
false
false
true
false
let elab_frame (c: comp_st) (frame: term) (e: R.term) =
let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_bind
val elab_bind (#g #x #c1 #c2 #c: _) (bc: bind_comp g x c1 c2 c) (e1 e2: R.term) : R.term
val elab_bind (#g #x #c1 #c2 #c: _) (bc: bind_comp g x c1 c2 c) (e1 e2: R.term) : R.term
let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 15, "end_line": 93, "start_col": 0, "start_line": 56 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
bc: Pulse.Typing.bind_comp g x c1 c2 c -> e1: FStar.Stubs.Reflection.Types.term -> e2: FStar.Stubs.Reflection.Types.term -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.var", "Pulse.Syntax.Base.comp", "Pulse.Typing.bind_comp", "FStar.Stubs.Reflection.Types.term", "Pulse.Syntax.Base.st_comp", "Pulse.Reflection.Util.mk_bind_stt", "Pulse.Syntax.Base.comp_u", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_pre", "Pulse.Reflection.Util.mk_abs", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Syntax.Base.comp_post", "Pulse.Reflection.Util.mk_bind_ghost", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.observability", "Pulse.Reflection.Util.mk_bind_atomic", "Pulse.Elaborate.Pure.elab_observability", "Pulse.Syntax.Base.comp_inames", "Pulse.Syntax.Base.comp_res" ]
[]
false
false
false
false
false
let elab_bind #g #x #c1 #c2 #c (bc: bind_comp g x c1 c2 c) (e1: R.term) (e2: R.term) : R.term =
let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_lift
val elab_lift (#g #c1 #c2: _) (d: lift_comp g c1 c2) (e: R.term) : Tot R.term
val elab_lift (#g #c1 #c2: _) (d: lift_comp g c1 c2) (e: R.term) : Tot R.term
let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term) : Tot R.term = match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 9, "end_line": 136, "start_col": 0, "start_line": 95 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
d: Pulse.Typing.lift_comp g c1 c2 -> e: FStar.Stubs.Reflection.Types.term -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.comp", "Pulse.Typing.lift_comp", "FStar.Stubs.Reflection.Types.term", "Pulse.Syntax.Base.comp_st", "Prims.b2t", "Pulse.Syntax.Base.uu___is_C_STAtomic", "Pulse.Reflection.Util.mk_lift_atomic_stt", "Pulse.Syntax.Base.comp_u", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_res", "Pulse.Reflection.Util.mk_abs", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.observability", "Pulse.Typing.sub_observability", "Pulse.Syntax.Base.__proj__C_STAtomic__item__obs", "Pulse.Reflection.Util.mk_lift_observability", "Pulse.Elaborate.Pure.elab_observability", "Pulse.Syntax.Base.comp_inames", "Pulse.Syntax.Base.comp_pre", "Pulse.Syntax.Base.uu___is_C_STGhost", "Pulse.Syntax.Base.term", "Pulse.Typing.tot_typing", "Pulse.Typing.non_informative_witness_t", "Pulse.Reflection.Util.mk_lift_ghost_neutral", "Prims.l_and", "Prims.eq2", "Pulse.Syntax.Base.Neutral", "Pulse.Reflection.Util.mk_lift_neutral_ghost" ]
[]
false
false
false
false
false
let elab_lift #g #c1 #c2 (d: lift_comp g c1 c2) (e: R.term) : Tot R.term =
match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a , reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.simple_arr
val simple_arr (t1 t2: R.term) : R.term
val simple_arr (t1 t2: R.term) : R.term
let simple_arr (t1 t2 : R.term) : R.term = let b = R.pack_binder { sort = t1; ppname = Sealed.seal "x"; qual = R.Q_Explicit; attrs = [] } in R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 55, "end_line": 155, "start_col": 0, "start_line": 149 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term) : Tot R.term = match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e let intro_pure_tm (p:term) = let open Pulse.Reflection.Util in wtag (Some STT_Ghost) (Tm_STApp { head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p; arg_qual = None; arg = tm_fstar (`()) Range.range_0 })
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
t1: FStar.Stubs.Reflection.Types.term -> t2: FStar.Stubs.Reflection.Types.term -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Builtins.pack_ln", "FStar.Stubs.Reflection.V2.Data.Tv_Arrow", "FStar.Stubs.Reflection.V2.Builtins.pack_comp", "FStar.Stubs.Reflection.V2.Data.C_Total", "FStar.Stubs.Reflection.Types.binder", "FStar.Stubs.Reflection.V2.Builtins.pack_binder", "FStar.Stubs.Reflection.V2.Data.Mkbinder_view", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Prims.Nil", "FStar.Sealed.seal", "Prims.string" ]
[]
false
false
false
true
false
let simple_arr (t1 t2: R.term) : R.term =
let b = R.pack_binder ({ sort = t1; ppname = Sealed.seal "x"; qual = R.Q_Explicit; attrs = [] }) in R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))
false
Vale.Stdcalls.X64.Aes.fst
Vale.Stdcalls.X64.Aes.lowstar_key128
val lowstar_key128:lowstar_key128_t
val lowstar_key128:lowstar_key128_t
let lowstar_key128 : lowstar_key128_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 4); IX64.wrap_weak_stdcall code_key128 dom (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win))
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 74, "end_line": 28, "start_col": 0, "start_line": 23 }
module Vale.Stdcalls.X64.Aes open FStar.Mul open FStar.HyperStack.ST module HS = FStar.HyperStack module B = LowStar.Buffer module DV = LowStar.BufferView.Down module UV = LowStar.BufferView.Up open Vale.Def.Types_s open Vale.Interop.Base module IX64 = Vale.Interop.X64 module VSig = Vale.AsLowStar.ValeSig module LSig = Vale.AsLowStar.LowStarSig module ME = Vale.X64.Memory module V = Vale.X64.Decls module IA = Vale.Interop.Assumptions module W = Vale.AsLowStar.Wrapper open Vale.X64.MemoryAdapters module VS = Vale.X64.State module MS = Vale.X64.Machine_s
{ "checked_file": "/", "dependencies": [ "Vale.X64.State.fsti.checked", "Vale.X64.MemoryAdapters.fsti.checked", "Vale.X64.Memory.fsti.checked", "Vale.X64.Machine_s.fst.checked", "Vale.X64.Decls.fsti.checked", "Vale.Interop.X64.fsti.checked", "Vale.Interop.Base.fst.checked", "Vale.Interop.Assumptions.fst.checked", "Vale.Def.Types_s.fst.checked", "Vale.AsLowStar.Wrapper.fsti.checked", "Vale.AsLowStar.ValeSig.fst.checked", "Vale.AsLowStar.LowStarSig.fst.checked", "prims.fst.checked", "LowStar.BufferView.Up.fsti.checked", "LowStar.BufferView.Down.fsti.checked", "LowStar.Buffer.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.List.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked" ], "interface_file": true, "source_file": "Vale.Stdcalls.X64.Aes.fst" }
[ { "abbrev": true, "full_module": "Vale.X64.Machine_s", "short_module": "MS" }, { "abbrev": true, "full_module": "Vale.X64.State", "short_module": "VS" }, { "abbrev": false, "full_module": "Vale.X64.MemoryAdapters", "short_module": null }, { "abbrev": true, "full_module": "Vale.AsLowStar.Wrapper", "short_module": "W" }, { "abbrev": true, "full_module": "Vale.Interop.Assumptions", "short_module": "IA" }, { "abbrev": true, "full_module": "Vale.X64.Decls", "short_module": "V" }, { "abbrev": true, "full_module": "Vale.X64.Memory", "short_module": "ME" }, { "abbrev": true, "full_module": "Vale.AsLowStar.LowStarSig", "short_module": "LSig" }, { "abbrev": true, "full_module": "Vale.AsLowStar.ValeSig", "short_module": "VSig" }, { "abbrev": true, "full_module": "Vale.Interop.X64", "short_module": "IX64" }, { "abbrev": false, "full_module": "Vale.Interop.Base", "short_module": null }, { "abbrev": false, "full_module": "Vale.Def.Types_s", "short_module": null }, { "abbrev": true, "full_module": "LowStar.BufferView.Up", "short_module": "UV" }, { "abbrev": true, "full_module": "LowStar.BufferView.Down", "short_module": "DV" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": true, "full_module": "Vale.AES.X64.AES", "short_module": "AE" }, { "abbrev": false, "full_module": "Vale.AES.AES_s", "short_module": null }, { "abbrev": true, "full_module": "Vale.X64.Machine_s", "short_module": "MS" }, { "abbrev": true, "full_module": "Vale.X64.State", "short_module": "VS" }, { "abbrev": false, "full_module": "Vale.X64.MemoryAdapters", "short_module": null }, { "abbrev": true, "full_module": "Vale.AsLowStar.Wrapper", "short_module": "W" }, { "abbrev": true, "full_module": "Vale.Interop.Assumptions", "short_module": "IA" }, { "abbrev": true, "full_module": "Vale.X64.Decls", "short_module": "V" }, { "abbrev": true, "full_module": "Vale.X64.Memory", "short_module": "ME" }, { "abbrev": true, "full_module": "Vale.AsLowStar.LowStarSig", "short_module": "LSig" }, { "abbrev": true, "full_module": "Vale.AsLowStar.ValeSig", "short_module": "VSig" }, { "abbrev": true, "full_module": "Vale.Interop.X64", "short_module": "IX64" }, { "abbrev": false, "full_module": "Vale.Interop.Base", "short_module": null }, { "abbrev": false, "full_module": "Vale.Def.Types_s", "short_module": null }, { "abbrev": true, "full_module": "LowStar.BufferView.Up", "short_module": "UV" }, { "abbrev": true, "full_module": "LowStar.BufferView.Down", "short_module": "DV" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Vale.Stdcalls.X64.Aes.lowstar_key128_t
Prims.Tot
[ "total" ]
[]
[ "Vale.Interop.X64.wrap_weak_stdcall", "Vale.Stdcalls.X64.Aes.code_key128", "Vale.Stdcalls.X64.Aes.dom", "Vale.AsLowStar.Wrapper.pre_rel_generic", "Vale.Interop.X64.max_stdcall", "Vale.Interop.X64.arg_reg_stdcall", "Prims.Nil", "Vale.Interop.Base.arg", "Vale.Stdcalls.X64.Aes.key128_pre", "Vale.AsLowStar.Wrapper.post_rel_generic", "Vale.Stdcalls.X64.Aes.key128_post", "Vale.AsLowStar.Wrapper.mk_prediction", "Vale.Interop.X64.regs_modified_stdcall", "Vale.Interop.X64.xmms_modified_stdcall", "Vale.Stdcalls.X64.Aes.key128_lemma", "Vale.Interop.Assumptions.win", "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "FStar.List.Tot.Base.length", "Vale.Interop.Base.td", "Prims.list" ]
[]
false
false
false
true
false
let lowstar_key128:lowstar_key128_t =
assert_norm (List.length dom + List.length ([] <: list arg) <= 4); IX64.wrap_weak_stdcall code_key128 dom (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win))
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_sub
val elab_sub : c1: Pulse.Syntax.Base.comp_st -> c2: Pulse.Syntax.Base.comp_st -> e: FStar.Stubs.Reflection.Types.term -> FStar.Stubs.Reflection.Types.term
let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 52, "end_line": 53, "start_col": 0, "start_line": 41 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
c1: Pulse.Syntax.Base.comp_st -> c2: Pulse.Syntax.Base.comp_st -> e: FStar.Stubs.Reflection.Types.term -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.comp_st", "FStar.Stubs.Reflection.Types.term", "Pulse.Syntax.Base.uu___is_C_ST", "Pulse.Reflection.Util.mk_sub_stt", "Prims.bool", "Pulse.Syntax.Base.uu___is_C_STAtomic", "Pulse.Reflection.Util.mk_sub_stt_atomic", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_inames", "Pulse.Reflection.Util.mk_sub_stt_ghost", "Pulse.Reflection.Util.mk_abs", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.comp_pre", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.comp_u", "Pulse.Syntax.Base.comp_res" ]
[]
false
false
false
true
false
let elab_sub (c1 c2: comp_st) (e: R.term) =
let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e
false
IfcRulesReify.fst
IfcRulesReify.inv_com'
val inv_com' (env: label_fun) (c: com) (l: label) (h0: heap) : Tot Type0
val inv_com' (env: label_fun) (c: com) (l: label) (h0: heap) : Tot Type0
let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 85, "end_line": 94, "start_col": 0, "start_line": 89 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> c: WhileReify.com -> l: IfcRulesReify.label -> h0: FStar.DM4F.Heap.IntStoreFixed.heap -> Type0
Prims.Tot
[ "total" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.com", "IfcRulesReify.label", "FStar.DM4F.Heap.IntStoreFixed.heap", "WhileReify.interpret_com", "Prims.l_True", "Prims.l_Forall", "FStar.DM4F.Heap.IntStoreFixed.id", "Prims.l_imp", "Prims.b2t", "IfcRulesReify.op_Less", "Prims.op_Equality", "Prims.int", "FStar.DM4F.Heap.IntStoreFixed.index" ]
[]
false
false
false
true
true
let inv_com' (env: label_fun) (c: com) (l: label) (h0: heap) : Tot Type0 =
match interpret_com h0 c with | None -> True | Some h1 -> forall (i: id). env i < l ==> index h0 i = index h1 i
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.intro_pure_tm
val intro_pure_tm : p: Pulse.Syntax.Base.term -> Pulse.Syntax.Base.st_term
let intro_pure_tm (p:term) = let open Pulse.Reflection.Util in wtag (Some STT_Ghost) (Tm_STApp { head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p; arg_qual = None; arg = tm_fstar (`()) Range.range_0 })
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 47, "end_line": 147, "start_col": 0, "start_line": 138 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term) : Tot R.term = match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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: Pulse.Syntax.Base.term -> Pulse.Syntax.Base.st_term
Prims.Tot
[ "total" ]
[]
[ "Pulse.Syntax.Base.term", "Pulse.Typing.wtag", "FStar.Pervasives.Native.Some", "Pulse.Syntax.Base.ctag", "Pulse.Syntax.Base.STT_Ghost", "Pulse.Syntax.Base.Tm_STApp", "Pulse.Syntax.Base.Mkst_term'__Tm_STApp__payload", "Pulse.Syntax.Pure.tm_pureapp", "Pulse.Syntax.Pure.tm_fvar", "Pulse.Syntax.Base.as_fv", "Pulse.Reflection.Util.mk_pulse_lib_core_lid", "FStar.Pervasives.Native.None", "Pulse.Syntax.Base.qualifier", "Pulse.Syntax.Base.tm_fstar", "FStar.Range.range_0", "Pulse.Syntax.Base.st_term" ]
[]
false
false
false
true
false
let intro_pure_tm (p: term) =
let open Pulse.Reflection.Util in wtag (Some STT_Ghost) (Tm_STApp ({ head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p; arg_qual = None; arg = tm_fstar (`()) Range.range_0 }))
false
IfcRulesReify.fst
IfcRulesReify.assign_inv_com'
val assign_inv_com' (env: label_fun) (e: exp) (r: id) (h0: heap) : Lemma (inv_com' env (Assign r e) (env r) h0)
val assign_inv_com' (env: label_fun) (e: exp) (r: id) (h0: heap) : Lemma (inv_com' env (Assign r e) (env r) h0)
let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v)
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 29, "end_line": 217, "start_col": 0, "start_line": 210 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> ()
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> r: FStar.DM4F.Heap.IntStoreFixed.id -> h0: FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (ensures IfcRulesReify.inv_com' env (WhileReify.Assign r e) (env r) h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "FStar.DM4F.Heap.IntStoreFixed.id", "FStar.DM4F.Heap.IntStoreFixed.heap", "WhileReify.interpret_com_st", "WhileReify.Assign", "Prims.unit", "Prims._assert", "Prims.eq2", "FStar.DM4F.Heap.IntStoreFixed.upd", "Prims.int", "WhileReify.interpret_exp_st", "Prims.l_True", "Prims.squash", "IfcRulesReify.inv_com'", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
false
false
true
false
false
let assign_inv_com' (env: label_fun) (e: exp) (r: id) (h0: heap) : Lemma (inv_com' env (Assign r e) (env r) h0) =
let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v)
false
IfcRulesReify.fst
IfcRulesReify.assign_com
val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r)))
val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r)))
let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r)
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 40, "end_line": 224, "start_col": 0, "start_line": 222 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r)))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> r: FStar.DM4F.Heap.IntStoreFixed.id -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e (env r)) (ensures IfcRulesReify.ni_com env (WhileReify.Assign r e) (env r))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "FStar.DM4F.Heap.IntStoreFixed.id", "FStar.Classical.forall_intro", "FStar.DM4F.Heap.IntStoreFixed.heap", "IfcRulesReify.inv_com'", "WhileReify.Assign", "IfcRulesReify.assign_inv_com'", "Prims.unit", "Rel.rel", "IfcRulesReify.ni_com'", "IfcRulesReify.assign_inv_com0", "FStar.Squash.get_proof", "IfcRulesReify.ni_exp" ]
[]
true
false
true
false
false
let assign_com env e r =
forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))); forall_intro (assign_inv_com' env e r)
false
IfcRulesReify.fst
IfcRulesReify.assign_inv_com0
val assign_inv_com0 (env: label_fun) (e: exp) (r: id) (ne: squash (ni_exp env e (env r))) (h0: rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0)
val assign_inv_com0 (env: label_fun) (e: exp) (r: id) (ne: squash (ni_exp env e (env r))) (h0: rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0)
let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> ()
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 17, "end_line": 208, "start_col": 0, "start_line": 196 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *)
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> r: FStar.DM4F.Heap.IntStoreFixed.id -> ne: Prims.squash (IfcRulesReify.ni_exp env e (env r)) -> h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (ensures IfcRulesReify.ni_com' env (WhileReify.Assign r e) (env r) h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "FStar.DM4F.Heap.IntStoreFixed.id", "Prims.squash", "IfcRulesReify.ni_exp", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "WhileReify.interpret_com_st", "WhileReify.Assign", "Rel.__proj__R__item__l", "Prims.unit", "Rel.__proj__R__item__r", "Prims._assert", "Prims.l_and", "Prims.b2t", "Prims.op_Equality", "FStar.DM4F.Heap.IntStoreFixed.upd", "Prims.int", "WhileReify.interpret_exp_st", "FStar.Squash.give_proof", "Prims.l_True", "IfcRulesReify.ni_com'", "Prims.Nil", "FStar.Pervasives.pattern" ]
[]
false
false
true
false
false
let assign_inv_com0 (env: label_fun) (e: exp) (r: id) (ne: squash (ni_exp env e (env r))) (h0: rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) =
FStar.Squash.give_proof ne; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> (match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> ()) | None, _ -> ()
false
Vale.Stdcalls.X64.Aes.fst
Vale.Stdcalls.X64.Aes.lowstar_key256
val lowstar_key256:lowstar_key256_t
val lowstar_key256:lowstar_key256_t
let lowstar_key256 : lowstar_key256_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 4); IX64.wrap_weak_stdcall code_key256 dom (W.mk_prediction code_key256 dom [] (key256_lemma code_key256 IA.win))
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 74, "end_line": 38, "start_col": 0, "start_line": 33 }
module Vale.Stdcalls.X64.Aes open FStar.Mul open FStar.HyperStack.ST module HS = FStar.HyperStack module B = LowStar.Buffer module DV = LowStar.BufferView.Down module UV = LowStar.BufferView.Up open Vale.Def.Types_s open Vale.Interop.Base module IX64 = Vale.Interop.X64 module VSig = Vale.AsLowStar.ValeSig module LSig = Vale.AsLowStar.LowStarSig module ME = Vale.X64.Memory module V = Vale.X64.Decls module IA = Vale.Interop.Assumptions module W = Vale.AsLowStar.Wrapper open Vale.X64.MemoryAdapters module VS = Vale.X64.State module MS = Vale.X64.Machine_s let lowstar_key128 : lowstar_key128_t = assert_norm (List.length dom + List.length ([]<:list arg) <= 4); IX64.wrap_weak_stdcall code_key128 dom (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win)) let aes128_key_expansion //: normal lowstar_key128_t = as_normal_t #lowstar_key128_t lowstar_key128
{ "checked_file": "/", "dependencies": [ "Vale.X64.State.fsti.checked", "Vale.X64.MemoryAdapters.fsti.checked", "Vale.X64.Memory.fsti.checked", "Vale.X64.Machine_s.fst.checked", "Vale.X64.Decls.fsti.checked", "Vale.Interop.X64.fsti.checked", "Vale.Interop.Base.fst.checked", "Vale.Interop.Assumptions.fst.checked", "Vale.Def.Types_s.fst.checked", "Vale.AsLowStar.Wrapper.fsti.checked", "Vale.AsLowStar.ValeSig.fst.checked", "Vale.AsLowStar.LowStarSig.fst.checked", "prims.fst.checked", "LowStar.BufferView.Up.fsti.checked", "LowStar.BufferView.Down.fsti.checked", "LowStar.Buffer.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.List.fst.checked", "FStar.HyperStack.ST.fsti.checked", "FStar.HyperStack.fst.checked" ], "interface_file": true, "source_file": "Vale.Stdcalls.X64.Aes.fst" }
[ { "abbrev": true, "full_module": "Vale.X64.Machine_s", "short_module": "MS" }, { "abbrev": true, "full_module": "Vale.X64.State", "short_module": "VS" }, { "abbrev": false, "full_module": "Vale.X64.MemoryAdapters", "short_module": null }, { "abbrev": true, "full_module": "Vale.AsLowStar.Wrapper", "short_module": "W" }, { "abbrev": true, "full_module": "Vale.Interop.Assumptions", "short_module": "IA" }, { "abbrev": true, "full_module": "Vale.X64.Decls", "short_module": "V" }, { "abbrev": true, "full_module": "Vale.X64.Memory", "short_module": "ME" }, { "abbrev": true, "full_module": "Vale.AsLowStar.LowStarSig", "short_module": "LSig" }, { "abbrev": true, "full_module": "Vale.AsLowStar.ValeSig", "short_module": "VSig" }, { "abbrev": true, "full_module": "Vale.Interop.X64", "short_module": "IX64" }, { "abbrev": false, "full_module": "Vale.Interop.Base", "short_module": null }, { "abbrev": false, "full_module": "Vale.Def.Types_s", "short_module": null }, { "abbrev": true, "full_module": "LowStar.BufferView.Up", "short_module": "UV" }, { "abbrev": true, "full_module": "LowStar.BufferView.Down", "short_module": "DV" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": true, "full_module": "Vale.AES.X64.AES", "short_module": "AE" }, { "abbrev": false, "full_module": "Vale.AES.AES_s", "short_module": null }, { "abbrev": true, "full_module": "Vale.X64.Machine_s", "short_module": "MS" }, { "abbrev": true, "full_module": "Vale.X64.State", "short_module": "VS" }, { "abbrev": false, "full_module": "Vale.X64.MemoryAdapters", "short_module": null }, { "abbrev": true, "full_module": "Vale.AsLowStar.Wrapper", "short_module": "W" }, { "abbrev": true, "full_module": "Vale.Interop.Assumptions", "short_module": "IA" }, { "abbrev": true, "full_module": "Vale.X64.Decls", "short_module": "V" }, { "abbrev": true, "full_module": "Vale.X64.Memory", "short_module": "ME" }, { "abbrev": true, "full_module": "Vale.AsLowStar.LowStarSig", "short_module": "LSig" }, { "abbrev": true, "full_module": "Vale.AsLowStar.ValeSig", "short_module": "VSig" }, { "abbrev": true, "full_module": "Vale.Interop.X64", "short_module": "IX64" }, { "abbrev": false, "full_module": "Vale.Interop.Base", "short_module": null }, { "abbrev": false, "full_module": "Vale.Def.Types_s", "short_module": null }, { "abbrev": true, "full_module": "LowStar.BufferView.Up", "short_module": "UV" }, { "abbrev": true, "full_module": "LowStar.BufferView.Down", "short_module": "DV" }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": true, "full_module": "FStar.HyperStack", "short_module": "HS" }, { "abbrev": true, "full_module": "LowStar.Buffer", "short_module": "B" }, { "abbrev": false, "full_module": "FStar.HyperStack.ST", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "short_module": null }, { "abbrev": false, "full_module": "Vale.Stdcalls.X64", "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": 0, "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": true, "smtencoding_l_arith_repr": "native", "smtencoding_nl_arith_repr": "wrapped", "smtencoding_valid_elim": false, "smtencoding_valid_intro": true, "tcnorm": true, "trivial_pre_for_unannotated_effectful_fns": false, "z3cliopt": [ "smt.arith.nl=false", "smt.QI.EAGER_THRESHOLD=100", "smt.CASE_SPLIT=3" ], "z3refresh": false, "z3rlimit": 5, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Vale.Stdcalls.X64.Aes.lowstar_key256_t
Prims.Tot
[ "total" ]
[]
[ "Vale.Interop.X64.wrap_weak_stdcall", "Vale.Stdcalls.X64.Aes.code_key256", "Vale.Stdcalls.X64.Aes.dom", "Vale.AsLowStar.Wrapper.pre_rel_generic", "Vale.Interop.X64.max_stdcall", "Vale.Interop.X64.arg_reg_stdcall", "Prims.Nil", "Vale.Interop.Base.arg", "Vale.Stdcalls.X64.Aes.key256_pre", "Vale.AsLowStar.Wrapper.post_rel_generic", "Vale.Stdcalls.X64.Aes.key256_post", "Vale.AsLowStar.Wrapper.mk_prediction", "Vale.Interop.X64.regs_modified_stdcall", "Vale.Interop.X64.xmms_modified_stdcall", "Vale.Stdcalls.X64.Aes.key256_lemma", "Vale.Interop.Assumptions.win", "Prims.unit", "FStar.Pervasives.assert_norm", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.op_Addition", "FStar.List.Tot.Base.length", "Vale.Interop.Base.td", "Prims.list" ]
[]
false
false
false
true
false
let lowstar_key256:lowstar_key256_t =
assert_norm (List.length dom + List.length ([] <: list arg) <= 4); IX64.wrap_weak_stdcall code_key256 dom (W.mk_prediction code_key256 dom [] (key256_lemma code_key256 IA.win))
false
IfcRulesReify.fst
IfcRulesReify.seq_com
val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l))
val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l))
let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 75, "end_line": 309, "start_col": 0, "start_line": 303 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
env: IfcRulesReify.label_fun -> c1: WhileReify.com -> c2: WhileReify.com -> l: IfcRulesReify.label -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_com env c1 l /\ IfcRulesReify.ni_com env c2 l) (ensures IfcRulesReify.ni_com env (WhileReify.Seq c1 c2) l)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.com", "IfcRulesReify.label", "FStar.Classical.forall_intro", "FStar.DM4F.Heap.IntStoreFixed.heap", "IfcRulesReify.inv_com'", "WhileReify.Seq", "IfcRulesReify.seq_inv_com'", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.Nil", "FStar.Pervasives.pattern", "Rel.rel", "IfcRulesReify.ni_com'", "IfcRulesReify.seq_com'" ]
[]
false
false
true
false
false
let seq_com env c1 c2 l =
forall_intro (fun (h0: rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)); forall_intro (fun (h0: heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0) )
false
IfcRulesReify.fst
IfcRulesReify.seq_inv_com'
val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0))
val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0))
let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> ()
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 23, "end_line": 256, "start_col": 0, "start_line": 250 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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
env: IfcRulesReify.label_fun -> c1: WhileReify.com -> c2: WhileReify.com -> l: IfcRulesReify.label -> h0: FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_com env c1 l /\ IfcRulesReify.ni_com env c2 l) (ensures IfcRulesReify.inv_com' env (WhileReify.Seq c1 c2) l h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.com", "IfcRulesReify.label", "FStar.DM4F.Heap.IntStoreFixed.heap", "WhileReify.interpret_com_st", "Prims.unit", "IfcRulesReify.seq_nil1", "IfcRulesReify.seq_nil2" ]
[]
false
false
true
false
false
let seq_inv_com' env c1 c2 l h0 =
match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> ()
false
IfcRulesReify.fst
IfcRulesReify.cond_inv_com'
val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0))
val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0))
let cond_inv_com' env e ct cf l h0 = let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 71, "end_line": 327, "start_col": 0, "start_line": 323 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l)) let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)) (* Typing rule for conditional commands env |- e : l env,pc:l |- ct env,pc:l |- cf ---------------------------------------------- env,pc:l |- if e <> 0 then ct else cf *) (* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *) val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l)))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> ct: WhileReify.com -> cf: WhileReify.com -> l: IfcRulesReify.label -> h0: FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\ IfcRulesReify.ni_com env ct l /\ IfcRulesReify.ni_com env cf l) (ensures IfcRulesReify.inv_com' env (WhileReify.If e ct cf) l h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "WhileReify.com", "IfcRulesReify.label", "FStar.DM4F.Heap.IntStoreFixed.heap", "Prims.op_Equality", "Prims.int", "Prims._assert", "Prims.l_imp", "IfcRulesReify.inv_com'", "WhileReify.If", "Prims.bool", "Prims.unit", "WhileReify.interpret_exp_st" ]
[]
false
false
true
false
false
let cond_inv_com' env e ct cf l h0 =
let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)
false
Pulse.Checker.IntroPure.fst
Pulse.Checker.IntroPure.check
val check (g:env) (pre:term) (pre_typing:tot_typing g pre tm_vprop) (post_hint:post_hint_opt g) (res_ppname:ppname) (t:st_term { Tm_IntroPure? t.term }) : T.Tac (checker_result_t g pre post_hint)
val check (g:env) (pre:term) (pre_typing:tot_typing g pre tm_vprop) (post_hint:post_hint_opt g) (res_ppname:ppname) (t:st_term { Tm_IntroPure? t.term }) : T.Tac (checker_result_t g pre post_hint)
let check (g:env) (pre:term) (pre_typing:tot_typing g pre tm_vprop) (post_hint:post_hint_opt g) (res_ppname:ppname) (t:st_term { Tm_IntroPure? t.term }) : T.Tac (checker_result_t g pre post_hint) = let g = Pulse.Typing.Env.push_context g "check_intro_pure" t.range in let Tm_IntroPure { p } = t.term in let (| p, p_typing |) = check_prop g p in let pv = check_prop_validity g p p_typing in let st_typing = T_IntroPure _ _ p_typing pv in prove_post_hint (try_frame_pre pre_typing (match_comp_res_with_post_hint st_typing post_hint) res_ppname) post_hint t.range
{ "file_name": "lib/steel/pulse/Pulse.Checker.IntroPure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 125, "end_line": 62, "start_col": 0, "start_line": 46 }
(* Copyright 2023 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 Pulse.Checker.IntroPure open Pulse.Syntax open Pulse.Typing open Pulse.Checker.Base open Pulse.Checker.Prover module T = FStar.Tactics.V2 module P = Pulse.Syntax.Printer let check_prop (g:env) (p:term) : T.Tac (p:term & tot_typing g p tm_prop) = let p0 = p in let (| p, p_typing |) = Pulse.Checker.Pure.check_vprop g (tm_pure p) in match p.t with | Tm_Pure pp -> let prop_typing = Pulse.Typing.Metatheory.pure_typing_inversion #_ #pp p_typing in (| pp, prop_typing |) | _ -> fail g None (Printf.sprintf "Impossible: check_intro_pure: checking a pure vprop %s returned a non-pure vprop %s,\ please file a bug-report" (P.term_to_string (tm_pure p0)) (P.term_to_string p)) let check_prop_validity (g:env) (p:term) (typing:tot_typing g p tm_prop): T.Tac (prop_validity g p) = Pulse.Checker.Pure.check_prop_validity g p typing
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.Metatheory.fsti.checked", "Pulse.Typing.Env.fsti.checked", "Pulse.Typing.fst.checked", "Pulse.Syntax.Printer.fsti.checked", "Pulse.Syntax.fst.checked", "Pulse.Checker.Pure.fsti.checked", "Pulse.Checker.Prover.fsti.checked", "Pulse.Checker.Base.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": true, "source_file": "Pulse.Checker.IntroPure.fst" }
[ { "abbrev": true, "full_module": "Pulse.Syntax.Printer", "short_module": "P" }, { "abbrev": false, "full_module": "Pulse.Checker.Prover", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "Pulse.Checker.Base", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker", "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: Pulse.Typing.Env.env -> pre: Pulse.Syntax.Base.term -> pre_typing: Pulse.Typing.tot_typing g pre Pulse.Syntax.Base.tm_vprop -> post_hint: Pulse.Typing.post_hint_opt g -> res_ppname: Pulse.Syntax.Base.ppname -> t: Pulse.Syntax.Base.st_term{Tm_IntroPure? (Mkst_term?.term t)} -> FStar.Tactics.Effect.Tac (Pulse.Checker.Base.checker_result_t g pre post_hint)
FStar.Tactics.Effect.Tac
[]
[]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.term", "Pulse.Typing.tot_typing", "Pulse.Syntax.Base.tm_vprop", "Pulse.Typing.post_hint_opt", "Pulse.Syntax.Base.ppname", "Pulse.Syntax.Base.st_term", "Prims.b2t", "Pulse.Syntax.Base.uu___is_Tm_IntroPure", "Pulse.Syntax.Base.__proj__Mkst_term__item__term", "Pulse.Typing.tm_prop", "Pulse.Checker.Prover.prove_post_hint", "Pulse.Syntax.Base.__proj__Mkst_term__item__range", "Pulse.Checker.Base.checker_result_t", "FStar.Pervasives.Native.None", "Pulse.Typing.post_hint_t", "Pulse.Checker.Prover.try_frame_pre", "FStar.Pervasives.dtuple3", "Pulse.Syntax.Base.comp_st", "Pulse.Typing.st_typing", "Pulse.Checker.Base.match_comp_res_with_post_hint", "Pulse.Typing.wtag", "FStar.Pervasives.Native.Some", "Pulse.Syntax.Base.ctag", "Pulse.Syntax.Base.STT_Ghost", "Pulse.Syntax.Base.Tm_IntroPure", "Pulse.Syntax.Base.Mkst_term'__Tm_IntroPure__payload", "Pulse.Typing.comp_intro_pure", "Pulse.Typing.T_IntroPure", "Pulse.Typing.prop_validity", "Pulse.Checker.IntroPure.check_prop_validity", "Prims.dtuple2", "Pulse.Checker.IntroPure.check_prop", "Pulse.Syntax.Base.st_term'", "Prims.eq2", "Pulse.Typing.Env.push_context" ]
[]
false
true
false
false
false
let check (g: env) (pre: term) (pre_typing: tot_typing g pre tm_vprop) (post_hint: post_hint_opt g) (res_ppname: ppname) (t: st_term{Tm_IntroPure? t.term}) : T.Tac (checker_result_t g pre post_hint) =
let g = Pulse.Typing.Env.push_context g "check_intro_pure" t.range in let Tm_IntroPure { p = p } = t.term in let (| p , p_typing |) = check_prop g p in let pv = check_prop_validity g p p_typing in let st_typing = T_IntroPure _ _ p_typing pv in prove_post_hint (try_frame_pre pre_typing (match_comp_res_with_post_hint st_typing post_hint) res_ppname) post_hint t.range
false
Hacl.Spec.SHA2.Lemmas.fst
Hacl.Spec.SHA2.Lemmas.transpose_state_lemma_ij
val transpose_state_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in (Seq.index (vec_v (transpose_state st).[ind / l])) (ind % l) == (Seq.index (state_spec_v st).[j] (i / word_length a)))
val transpose_state_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in (Seq.index (vec_v (transpose_state st).[ind / l])) (ind % l) == (Seq.index (state_spec_v st).[j] (i / word_length a)))
let transpose_state_lemma_ij #a #m st j i = match lanes a m with | 1 -> () | 4 -> transpose_state4_lemma #a #m st j i | 8 -> transpose_state8_lemma #a #m st j i
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 44, "end_line": 136, "start_col": 0, "start_line": 132 }
module Hacl.Spec.SHA2.Lemmas open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector open Lib.IntVector.Transpose open Spec.Hash.Definitions open Hacl.Spec.SHA2.Vec #set-options "--z3rlimit 50 --fuel 0 --ifuel 1" val transpose_ws4_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16 -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws4_lemma_ij #a #m ws j i = let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs); //assert ((transpose_ws4 ws).[i] == (sub (transpose_ws4 ws) (i_sub * l) l).[j_sub]); //assert ((transpose_ws4 ws).[i] == (transpose4x4_lseq vs).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v (transpose4x4_lseq vs).[j_sub]).[j]); transpose4x4_lemma vs; assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v vs.[j]).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i_sub * l + j]).[j_sub]) val transpose_ws8_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 8} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws8_lemma_ij #a #m ws j i = let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws8 ws) (i_sub * l) l) (transpose8x8_lseq vs); assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v (transpose8x8_lseq vs).[j_sub]).[j]); transpose8x8_lemma vs; assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i_sub * lanes a m + j]).[j_sub]) val transpose_ws_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws_lemma_ij #a #m ws j i = assert (((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v (transpose_ws ws).[i]).[j]); match lanes a m with | 1 -> () | 4 -> transpose_ws4_lemma_ij #a #m ws j i | 8 -> transpose_ws8_lemma_ij #a #m ws j i val transpose_state4_lemma: #a:sha2_alg -> #m:m_spec{lanes a m == 4} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in Seq.index (vec_v (transpose_state st).[ind / l]) (ind % l) == Seq.index (state_spec_v st).[j] (i / word_length a)) let transpose_state4_lemma #a #m st j i = let r0 = transpose4x4_lseq (sub st 0 4) in transpose4x4_lemma (sub st 0 4); let r1 = transpose4x4_lseq (sub st 4 4) in transpose4x4_lemma (sub st 4 4) val transpose_state8_lemma: #a:sha2_alg -> #m:m_spec{lanes a m == 8} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in Seq.index (vec_v (transpose_state8 st).[ind / l]) (ind % l) == Seq.index (state_spec_v st).[j] (i / word_length a)) let transpose_state8_lemma #a #m st j i = let l = lanes a m in let ind = 8 * j + i / word_length a in let r0 = transpose8x8_lseq st in transpose8x8_lemma st val transpose_state_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in (Seq.index (vec_v (transpose_state st).[ind / l])) (ind % l) == (Seq.index (state_spec_v st).[j] (i / word_length a)))
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.Transpose.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "Hacl.Spec.SHA2.Vec.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.SHA2.Lemmas.fst" }
[ { "abbrev": false, "full_module": "Hacl.Spec.SHA2.Vec", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector.Transpose", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "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": 1, "max_fuel": 0, "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
st: Hacl.Spec.SHA2.Vec.state_spec a m -> j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} -> i: Prims.nat{i < 8 * Spec.Hash.Definitions.word_length a} -> FStar.Pervasives.Lemma (ensures (let l = Hacl.Spec.SHA2.Vec.lanes a m in let ind = 8 * j + i / Spec.Hash.Definitions.word_length a in FStar.Seq.Base.index (Lib.IntVector.vec_v (Hacl.Spec.SHA2.Vec.transpose_state st).[ ind / l ]) (ind % l) == FStar.Seq.Base.index (Hacl.Spec.SHA2.Vec.state_spec_v st).[ j ] (i / Spec.Hash.Definitions.word_length a)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Spec.Hash.Definitions.sha2_alg", "Hacl.Spec.SHA2.Vec.m_spec", "Hacl.Spec.SHA2.Vec.is_supported", "Hacl.Spec.SHA2.Vec.state_spec", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "Hacl.Spec.SHA2.Vec.lanes", "FStar.Mul.op_Star", "Spec.Hash.Definitions.word_length", "Hacl.Spec.SHA2.Lemmas.transpose_state4_lemma", "Hacl.Spec.SHA2.Lemmas.transpose_state8_lemma", "Prims.unit" ]
[]
false
false
true
false
false
let transpose_state_lemma_ij #a #m st j i =
match lanes a m with | 1 -> () | 4 -> transpose_state4_lemma #a #m st j i | 8 -> transpose_state8_lemma #a #m st j i
false
IfcRulesReify.fst
IfcRulesReify.cond_com
val cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com env (If e ct cf) l))
val cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com env (If e ct cf) l))
let cond_com env e ct cf l = forall_intro (fun (h0:rel heap) -> cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ; forall_intro (fun (h0:heap) -> cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0))
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 79, "end_line": 387, "start_col": 0, "start_line": 381 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l)) let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)) (* Typing rule for conditional commands env |- e : l env,pc:l |- ct env,pc:l |- cf ---------------------------------------------- env,pc:l |- if e <> 0 then ct else cf *) (* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *) val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0)) let cond_inv_com' env e ct cf l h0 = let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0) (* Works too but takes 20s more *) (* let c = if v = 0 then cf else ct in *) (* match reify (interpret_com_st c h0) h0 with *) (* | None, _ -> () *) (* | Some (), h1 -> () *) #reset-options "--max_fuel 1" let interpret_cond (e:exp) (ct:com) (cf:com) (h:heap) : Lemma (let v = reify (interpret_exp_st e) h in let c = if v = 0 then cf else ct in (reify (interpret_com_st (If e ct cf) h) h == reify (interpret_com_st c h) h)) = () val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com' env (If e ct cf) l h0)) let cond_ni_com' env e ct cf l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else let R h0l h0r = h0 in let vl = reify (interpret_exp_st e) h0l in let vr = reify (interpret_exp_st e) h0r in if Low? l then begin assert (vl == vr) ; let c = if vl = 0 then cf else ct in assert (ni_com env c l) ; let cif = If e ct cf in //NS:05/15 ... this 2 should be trivial to prove. // Why do they require a lemma? interpret_cond e ct cf h0l; interpret_cond e ct cf h0r; use_ni_com env c l (R h0l h0r) end else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) match reify (interpret_com_st (If e ct cf) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (If e ct cf) h0r) h0r with | None, _ -> () | Some (), h1r -> cond_inv_com' env e ct cf l h0l ; cond_inv_com' env e ct cf l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) #set-options "--z3rlimit 5" val cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l)))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 1, "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
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> ct: WhileReify.com -> cf: WhileReify.com -> l: IfcRulesReify.label -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\ IfcRulesReify.ni_com env ct l /\ IfcRulesReify.ni_com env cf l) (ensures IfcRulesReify.ni_com env (WhileReify.If e ct cf) l)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "WhileReify.com", "IfcRulesReify.label", "FStar.Classical.forall_intro", "FStar.DM4F.Heap.IntStoreFixed.heap", "IfcRulesReify.inv_com'", "WhileReify.If", "IfcRulesReify.cond_inv_com'", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.Nil", "FStar.Pervasives.pattern", "Rel.rel", "IfcRulesReify.ni_com'", "IfcRulesReify.cond_ni_com'" ]
[]
false
false
true
false
false
let cond_com env e ct cf l =
forall_intro (fun (h0: rel heap) -> cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)); forall_intro (fun (h0: heap) -> cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0))
false
IfcRulesReify.fst
IfcRulesReify.while_com
val while_com : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (ni_com env (While e c v) l))
val while_com : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (ni_com env (While e c v) l))
let while_com env e c v l = forall_intro (fun (h:rel heap) -> while_ni_com' env e c v l h <: Lemma (ensures (ni_com' env (While e c v) l h))) ; forall_intro (fun (h0:heap) -> while_inv_com' env e c v l h0 <: Lemma (ensures (inv_com' env (While e c v) l h0)))
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 89, "end_line": 524, "start_col": 0, "start_line": 518 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l)) let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)) (* Typing rule for conditional commands env |- e : l env,pc:l |- ct env,pc:l |- cf ---------------------------------------------- env,pc:l |- if e <> 0 then ct else cf *) (* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *) val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0)) let cond_inv_com' env e ct cf l h0 = let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0) (* Works too but takes 20s more *) (* let c = if v = 0 then cf else ct in *) (* match reify (interpret_com_st c h0) h0 with *) (* | None, _ -> () *) (* | Some (), h1 -> () *) #reset-options "--max_fuel 1" let interpret_cond (e:exp) (ct:com) (cf:com) (h:heap) : Lemma (let v = reify (interpret_exp_st e) h in let c = if v = 0 then cf else ct in (reify (interpret_com_st (If e ct cf) h) h == reify (interpret_com_st c h) h)) = () val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com' env (If e ct cf) l h0)) let cond_ni_com' env e ct cf l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else let R h0l h0r = h0 in let vl = reify (interpret_exp_st e) h0l in let vr = reify (interpret_exp_st e) h0r in if Low? l then begin assert (vl == vr) ; let c = if vl = 0 then cf else ct in assert (ni_com env c l) ; let cif = If e ct cf in //NS:05/15 ... this 2 should be trivial to prove. // Why do they require a lemma? interpret_cond e ct cf h0l; interpret_cond e ct cf h0r; use_ni_com env c l (R h0l h0r) end else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) match reify (interpret_com_st (If e ct cf) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (If e ct cf) h0r) h0r with | None, _ -> () | Some (), h1r -> cond_inv_com' env e ct cf l h0l ; cond_inv_com' env e ct cf l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) #set-options "--z3rlimit 5" val cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com env (If e ct cf) l)) let cond_com env e ct cf l = forall_intro (fun (h0:rel heap) -> cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ; forall_intro (fun (h0:heap) -> cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0)) (* Typing rule for Skip ------------------- env,pc:High |- skip *) val skip_com : env:label_fun -> Lemma (ni_com env Skip High) let skip_com _ = () (* While rule for commands env |- e : l env,pc:l |- c ----------------------------------- env,pc:l |- while (e <> 0) do c *) val while_inv_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (inv_com' env (While e c v) l h0)) (decreases (decr_while h0 (While e c v))) #reset-options "--z3rlimit 40" let interpret_while_nil e c v h : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ fst (reify (interpret_com_st c h) h) == None)) (ensures (interpret_com h (While e c v) == None)) = () let interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap) : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ (match reify (interpret_com_st c h) h with | None, _ -> True | Some _, h' -> interpret_exp' h' v >= interpret_exp' h v))) (ensures (interpret_com h (While e c v) == None)) = () let rec while_inv_com' env e c v l h0 = let v0 = reify (interpret_exp_st e) h0 in if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0) else let m0 = interpret_exp' h0 v in match reify (interpret_com_st c h0) h0 with | None, _ -> interpret_while_nil e c v h0 | Some (), h2 -> let m1 = interpret_exp' h2 v in if m0 > m1 then begin assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ; while_inv_com' env e c v l h2 end else interpret_while_loops e c v h0 val while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ High? l)) (ensures (ni_com' env (While e c v) l h0)) let while_ni_com'_low_equiv_high env e c v l h0 = (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) let R h0l h0r = h0 in match reify (interpret_com_st (While e c v) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (While e c v) h0r) h0r with | None, _ -> () | Some (), h1r -> while_inv_com' env e c v l h0l ; while_inv_com' env e c v l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) val while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ Low? l)) (ensures (ni_com' env (While e c v) l h0)) (decreases (decr_while (R?.l h0) (While e c v) + decr_while (R?.r h0) (While e c v))) let rec while_ni_com'_low_equiv_low env e c v l h0 = let R h0l h0r = h0 in let v0l = reify (interpret_exp_st e) h0l in let v0r = reify (interpret_exp_st e) h0r in assert (v0l == v0r) ; if v0l = 0 then begin assert (interpret_com h0l (While e c v) == Some h0l); assert (interpret_com h0r (While e c v) == Some h0r) end else let m0l = interpret_exp' h0l v in let m0r = interpret_exp' h0r v in match reify (interpret_com_st c h0l) h0l with | None, _ -> interpret_while_nil e c v h0l | Some (), h2l -> match reify (interpret_com_st c h0r) h0r with | None, _ -> interpret_while_nil e c v h0r | Some (), h2r -> let m1l = interpret_exp' h2l v in let m1r = interpret_exp' h2r v in if m0l > m1l then if m0r > m1r then begin assert (decr_while h2l (While e c v) << decr_while h0l (While e c v)) ; while_ni_com'_low_equiv_low env e c v l (R h2l h2r) end else interpret_while_loops e c v h0r else interpret_while_loops e c v h0l val while_ni_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (ni_com' env (While e c v) l h0)) #set-options "--max_fuel 1 --max_ifuel 1 --z3rlimit 50" let while_ni_com' env e c v l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else if Low? l then while_ni_com'_low_equiv_low env e c v l h0 else while_ni_com'_low_equiv_high env e c v l h0 #set-options "--z3rlimit 5" val while_com : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> Lemma (requires (ni_exp env e l /\ ni_com env c l))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 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
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> c: WhileReify.com -> v: WhileReify.metric -> l: IfcRulesReify.label -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\ IfcRulesReify.ni_com env c l) (ensures IfcRulesReify.ni_com env (WhileReify.While e c v) l)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "WhileReify.com", "WhileReify.metric", "IfcRulesReify.label", "FStar.Classical.forall_intro", "FStar.DM4F.Heap.IntStoreFixed.heap", "IfcRulesReify.inv_com'", "WhileReify.While", "IfcRulesReify.while_inv_com'", "Prims.unit", "Prims.l_True", "Prims.squash", "Prims.Nil", "FStar.Pervasives.pattern", "Rel.rel", "IfcRulesReify.ni_com'", "IfcRulesReify.while_ni_com'" ]
[]
false
false
true
false
false
let while_com env e c v l =
forall_intro (fun (h: rel heap) -> while_ni_com' env e c v l h <: Lemma (ensures (ni_com' env (While e c v) l h))); forall_intro (fun (h0: heap) -> while_inv_com' env e c v l h0 <: Lemma (ensures (inv_com' env (While e c v) l h0)))
false
IfcRulesReify.fst
IfcRulesReify.cond_ni_com'
val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com' env (If e ct cf) l h0))
val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com' env (If e ct cf) l h0))
let cond_ni_com' env e ct cf l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else let R h0l h0r = h0 in let vl = reify (interpret_exp_st e) h0l in let vr = reify (interpret_exp_st e) h0r in if Low? l then begin assert (vl == vr) ; let c = if vl = 0 then cf else ct in assert (ni_com env c l) ; let cif = If e ct cf in //NS:05/15 ... this 2 should be trivial to prove. // Why do they require a lemma? interpret_cond e ct cf h0l; interpret_cond e ct cf h0r; use_ni_com env c l (R h0l h0r) end else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) match reify (interpret_com_st (If e ct cf) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (If e ct cf) h0r) h0r with | None, _ -> () | Some (), h1r -> cond_inv_com' env e ct cf l h0l ; cond_inv_com' env e ct cf l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 65, "end_line": 374, "start_col": 0, "start_line": 346 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l)) let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)) (* Typing rule for conditional commands env |- e : l env,pc:l |- ct env,pc:l |- cf ---------------------------------------------- env,pc:l |- if e <> 0 then ct else cf *) (* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *) val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0)) let cond_inv_com' env e ct cf l h0 = let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0) (* Works too but takes 20s more *) (* let c = if v = 0 then cf else ct in *) (* match reify (interpret_com_st c h0) h0 with *) (* | None, _ -> () *) (* | Some (), h1 -> () *) #reset-options "--max_fuel 1" let interpret_cond (e:exp) (ct:com) (cf:com) (h:heap) : Lemma (let v = reify (interpret_exp_st e) h in let c = if v = 0 then cf else ct in (reify (interpret_com_st (If e ct cf) h) h == reify (interpret_com_st c h) h)) = () val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l)))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 1, "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
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> ct: WhileReify.com -> cf: WhileReify.com -> l: IfcRulesReify.label -> h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\ IfcRulesReify.ni_com env ct l /\ IfcRulesReify.ni_com env cf l) (ensures IfcRulesReify.ni_com' env (WhileReify.If e ct cf) l h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "WhileReify.com", "IfcRulesReify.label", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "Prims.op_Negation", "FStar.StrongExcludedMiddle.strong_excluded_middle", "IfcRulesReify.low_equiv", "Prims.bool", "IfcRulesReify.uu___is_Low", "IfcRulesReify.use_ni_com", "Rel.R", "Prims.unit", "IfcRulesReify.interpret_cond", "WhileReify.If", "Prims._assert", "IfcRulesReify.ni_com", "Prims.op_Equality", "Prims.int", "Prims.eq2", "WhileReify.interpret_com_st", "Prims.l_imp", "IfcRulesReify.cond_inv_com'", "WhileReify.interpret_exp_st" ]
[]
false
false
true
false
false
let cond_ni_com' env e ct cf l h0 =
if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else let R h0l h0r = h0 in let vl = reify (interpret_exp_st e) h0l in let vr = reify (interpret_exp_st e) h0r in if Low? l then (assert (vl == vr); let c = if vl = 0 then cf else ct in assert (ni_com env c l); let cif = If e ct cf in interpret_cond e ct cf h0l; interpret_cond e ct cf h0r; use_ni_com env c l (R h0l h0r)) else match reify (interpret_com_st (If e ct cf) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (If e ct cf) h0r) h0r with | None, _ -> () | Some (), h1r -> cond_inv_com' env e ct cf l h0l; cond_inv_com' env e ct cf l h0r; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))
false
IfcRulesReify.fst
IfcRulesReify.seq_com'
val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0))
val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0))
let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 6, "end_line": 298, "start_col": 0, "start_line": 274 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
env: IfcRulesReify.label_fun -> c1: WhileReify.com -> c2: WhileReify.com -> l: IfcRulesReify.label -> h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_com env c1 l /\ IfcRulesReify.ni_com env c2 l) (ensures IfcRulesReify.ni_com' env (WhileReify.Seq c1 c2) l h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.com", "IfcRulesReify.label", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "Prims.op_Negation", "FStar.StrongExcludedMiddle.strong_excluded_middle", "IfcRulesReify.low_equiv", "Prims.bool", "WhileReify.interpret_com_st", "Prims.unit", "IfcRulesReify.seq_nil1", "IfcRulesReify.seq_nil2", "Prims._assert", "IfcRulesReify.use_ni_com", "Rel.R" ]
[]
false
false
true
false
false
let seq_com' env c1 c2 l h0 =
if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else (assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1); let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2))
false
IfcRulesReify.fst
IfcRulesReify.while_ni_com'
val while_ni_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (ni_com' env (While e c v) l h0))
val while_ni_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (ni_com' env (While e c v) l h0))
let while_ni_com' env e c v l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else if Low? l then while_ni_com'_low_equiv_low env e c v l h0 else while_ni_com'_low_equiv_high env e c v l h0
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 50, "end_line": 511, "start_col": 0, "start_line": 506 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l)) let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)) (* Typing rule for conditional commands env |- e : l env,pc:l |- ct env,pc:l |- cf ---------------------------------------------- env,pc:l |- if e <> 0 then ct else cf *) (* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *) val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0)) let cond_inv_com' env e ct cf l h0 = let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0) (* Works too but takes 20s more *) (* let c = if v = 0 then cf else ct in *) (* match reify (interpret_com_st c h0) h0 with *) (* | None, _ -> () *) (* | Some (), h1 -> () *) #reset-options "--max_fuel 1" let interpret_cond (e:exp) (ct:com) (cf:com) (h:heap) : Lemma (let v = reify (interpret_exp_st e) h in let c = if v = 0 then cf else ct in (reify (interpret_com_st (If e ct cf) h) h == reify (interpret_com_st c h) h)) = () val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com' env (If e ct cf) l h0)) let cond_ni_com' env e ct cf l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else let R h0l h0r = h0 in let vl = reify (interpret_exp_st e) h0l in let vr = reify (interpret_exp_st e) h0r in if Low? l then begin assert (vl == vr) ; let c = if vl = 0 then cf else ct in assert (ni_com env c l) ; let cif = If e ct cf in //NS:05/15 ... this 2 should be trivial to prove. // Why do they require a lemma? interpret_cond e ct cf h0l; interpret_cond e ct cf h0r; use_ni_com env c l (R h0l h0r) end else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) match reify (interpret_com_st (If e ct cf) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (If e ct cf) h0r) h0r with | None, _ -> () | Some (), h1r -> cond_inv_com' env e ct cf l h0l ; cond_inv_com' env e ct cf l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) #set-options "--z3rlimit 5" val cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com env (If e ct cf) l)) let cond_com env e ct cf l = forall_intro (fun (h0:rel heap) -> cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ; forall_intro (fun (h0:heap) -> cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0)) (* Typing rule for Skip ------------------- env,pc:High |- skip *) val skip_com : env:label_fun -> Lemma (ni_com env Skip High) let skip_com _ = () (* While rule for commands env |- e : l env,pc:l |- c ----------------------------------- env,pc:l |- while (e <> 0) do c *) val while_inv_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (inv_com' env (While e c v) l h0)) (decreases (decr_while h0 (While e c v))) #reset-options "--z3rlimit 40" let interpret_while_nil e c v h : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ fst (reify (interpret_com_st c h) h) == None)) (ensures (interpret_com h (While e c v) == None)) = () let interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap) : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ (match reify (interpret_com_st c h) h with | None, _ -> True | Some _, h' -> interpret_exp' h' v >= interpret_exp' h v))) (ensures (interpret_com h (While e c v) == None)) = () let rec while_inv_com' env e c v l h0 = let v0 = reify (interpret_exp_st e) h0 in if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0) else let m0 = interpret_exp' h0 v in match reify (interpret_com_st c h0) h0 with | None, _ -> interpret_while_nil e c v h0 | Some (), h2 -> let m1 = interpret_exp' h2 v in if m0 > m1 then begin assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ; while_inv_com' env e c v l h2 end else interpret_while_loops e c v h0 val while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ High? l)) (ensures (ni_com' env (While e c v) l h0)) let while_ni_com'_low_equiv_high env e c v l h0 = (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) let R h0l h0r = h0 in match reify (interpret_com_st (While e c v) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (While e c v) h0r) h0r with | None, _ -> () | Some (), h1r -> while_inv_com' env e c v l h0l ; while_inv_com' env e c v l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) val while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ Low? l)) (ensures (ni_com' env (While e c v) l h0)) (decreases (decr_while (R?.l h0) (While e c v) + decr_while (R?.r h0) (While e c v))) let rec while_ni_com'_low_equiv_low env e c v l h0 = let R h0l h0r = h0 in let v0l = reify (interpret_exp_st e) h0l in let v0r = reify (interpret_exp_st e) h0r in assert (v0l == v0r) ; if v0l = 0 then begin assert (interpret_com h0l (While e c v) == Some h0l); assert (interpret_com h0r (While e c v) == Some h0r) end else let m0l = interpret_exp' h0l v in let m0r = interpret_exp' h0r v in match reify (interpret_com_st c h0l) h0l with | None, _ -> interpret_while_nil e c v h0l | Some (), h2l -> match reify (interpret_com_st c h0r) h0r with | None, _ -> interpret_while_nil e c v h0r | Some (), h2r -> let m1l = interpret_exp' h2l v in let m1r = interpret_exp' h2r v in if m0l > m1l then if m0r > m1r then begin assert (decr_while h2l (While e c v) << decr_while h0l (While e c v)) ; while_ni_com'_low_equiv_low env e c v l (R h2l h2r) end else interpret_while_loops e c v h0r else interpret_while_loops e c v h0l val while_ni_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (ni_com' env (While e c v) l h0))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 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": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> c: WhileReify.com -> v: WhileReify.metric -> l: IfcRulesReify.label -> h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\ IfcRulesReify.ni_com env c l) (ensures IfcRulesReify.ni_com' env (WhileReify.While e c v) l h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "WhileReify.com", "WhileReify.metric", "IfcRulesReify.label", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "Prims.op_Negation", "FStar.StrongExcludedMiddle.strong_excluded_middle", "IfcRulesReify.low_equiv", "Prims.bool", "IfcRulesReify.uu___is_Low", "IfcRulesReify.while_ni_com'_low_equiv_low", "IfcRulesReify.while_ni_com'_low_equiv_high", "Prims.unit" ]
[]
false
false
true
false
false
let while_ni_com' env e c v l h0 =
if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else if Low? l then while_ni_com'_low_equiv_low env e c v l h0 else while_ni_com'_low_equiv_high env e c v l h0
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.and_elim'
val and_elim' (h: binding) : Tac unit
val and_elim' (h: binding) : Tac unit
let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 9, "end_line": 145, "start_col": 0, "start_line": 143 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
h: FStar.Tactics.NamedView.binding -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.binding", "FStar.Stubs.Tactics.V2.Builtins.clear", "Prims.unit", "FStar.Tactics.V2.Logic.and_elim", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Var", "FStar.Tactics.V2.SyntaxCoercions.binding_to_namedv" ]
[]
false
true
false
false
false
let and_elim' (h: binding) : Tac unit =
and_elim (pack (Tv_Var h)); clear h
false
IfcRulesReify.fst
IfcRulesReify.while_ni_com'_low_equiv_high
val while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ High? l)) (ensures (ni_com' env (While e c v) l h0))
val while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ High? l)) (ensures (ni_com' env (While e c v) l h0))
let while_ni_com'_low_equiv_high env e c v l h0 = (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) let R h0l h0r = h0 in match reify (interpret_com_st (While e c v) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (While e c v) h0r) h0r with | None, _ -> () | Some (), h1r -> while_inv_com' env e c v l h0l ; while_inv_com' env e c v l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 61, "end_line": 467, "start_col": 0, "start_line": 456 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l)) let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)) (* Typing rule for conditional commands env |- e : l env,pc:l |- ct env,pc:l |- cf ---------------------------------------------- env,pc:l |- if e <> 0 then ct else cf *) (* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *) val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0)) let cond_inv_com' env e ct cf l h0 = let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0) (* Works too but takes 20s more *) (* let c = if v = 0 then cf else ct in *) (* match reify (interpret_com_st c h0) h0 with *) (* | None, _ -> () *) (* | Some (), h1 -> () *) #reset-options "--max_fuel 1" let interpret_cond (e:exp) (ct:com) (cf:com) (h:heap) : Lemma (let v = reify (interpret_exp_st e) h in let c = if v = 0 then cf else ct in (reify (interpret_com_st (If e ct cf) h) h == reify (interpret_com_st c h) h)) = () val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com' env (If e ct cf) l h0)) let cond_ni_com' env e ct cf l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else let R h0l h0r = h0 in let vl = reify (interpret_exp_st e) h0l in let vr = reify (interpret_exp_st e) h0r in if Low? l then begin assert (vl == vr) ; let c = if vl = 0 then cf else ct in assert (ni_com env c l) ; let cif = If e ct cf in //NS:05/15 ... this 2 should be trivial to prove. // Why do they require a lemma? interpret_cond e ct cf h0l; interpret_cond e ct cf h0r; use_ni_com env c l (R h0l h0r) end else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) match reify (interpret_com_st (If e ct cf) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (If e ct cf) h0r) h0r with | None, _ -> () | Some (), h1r -> cond_inv_com' env e ct cf l h0l ; cond_inv_com' env e ct cf l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) #set-options "--z3rlimit 5" val cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com env (If e ct cf) l)) let cond_com env e ct cf l = forall_intro (fun (h0:rel heap) -> cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ; forall_intro (fun (h0:heap) -> cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0)) (* Typing rule for Skip ------------------- env,pc:High |- skip *) val skip_com : env:label_fun -> Lemma (ni_com env Skip High) let skip_com _ = () (* While rule for commands env |- e : l env,pc:l |- c ----------------------------------- env,pc:l |- while (e <> 0) do c *) val while_inv_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (inv_com' env (While e c v) l h0)) (decreases (decr_while h0 (While e c v))) #reset-options "--z3rlimit 40" let interpret_while_nil e c v h : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ fst (reify (interpret_com_st c h) h) == None)) (ensures (interpret_com h (While e c v) == None)) = () let interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap) : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ (match reify (interpret_com_st c h) h with | None, _ -> True | Some _, h' -> interpret_exp' h' v >= interpret_exp' h v))) (ensures (interpret_com h (While e c v) == None)) = () let rec while_inv_com' env e c v l h0 = let v0 = reify (interpret_exp_st e) h0 in if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0) else let m0 = interpret_exp' h0 v in match reify (interpret_com_st c h0) h0 with | None, _ -> interpret_while_nil e c v h0 | Some (), h2 -> let m1 = interpret_exp' h2 v in if m0 > m1 then begin assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ; while_inv_com' env e c v l h2 end else interpret_while_loops e c v h0 val while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ High? l))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 40, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> c: WhileReify.com -> v: WhileReify.metric -> l: IfcRulesReify.label -> h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\ IfcRulesReify.ni_com env c l /\ IfcRulesReify.low_equiv env h0 /\ High? l) (ensures IfcRulesReify.ni_com' env (WhileReify.While e c v) l h0)
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "WhileReify.com", "WhileReify.metric", "IfcRulesReify.label", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "WhileReify.interpret_com_st", "WhileReify.While", "Prims.unit", "Prims._assert", "Prims.l_imp", "IfcRulesReify.low_equiv", "Rel.R", "IfcRulesReify.while_inv_com'" ]
[]
false
false
true
false
false
let while_ni_com'_low_equiv_high env e c v l h0 =
let R h0l h0r = h0 in match reify (interpret_com_st (While e c v) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (While e c v) h0r) h0r with | None, _ -> () | Some (), h1r -> while_inv_com' env e c v l h0l; while_inv_com' env e c v l h0r; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.repeat'
val repeat' (#a: _) (f: (unit -> Tac a)) : Tac unit
val repeat' (#a: _) (f: (unit -> Tac a)) : Tac unit
let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in ()
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 24, "end_line": 141, "start_col": 0, "start_line": 140 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in ()
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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: (_: Prims.unit -> FStar.Tactics.Effect.Tac a) -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Prims.list", "FStar.Tactics.V2.Derived.repeat" ]
[]
false
true
false
false
false
let repeat' #a (f: (unit -> Tac a)) : Tac unit =
let _ = repeat f in ()
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.implies_intro'
val implies_intro': Prims.unit -> Tac unit
val implies_intro': Prims.unit -> Tac unit
let implies_intro' () : Tac unit = let _ = implies_intro () in ()
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 32, "end_line": 138, "start_col": 0, "start_line": 137 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect.
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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.binding", "FStar.Tactics.V2.Logic.implies_intro" ]
[]
false
true
false
false
false
let implies_intro' () : Tac unit =
let _ = implies_intro () in ()
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.exact_hyp'
val exact_hyp' (h: namedv) : Tac unit
val exact_hyp' (h: namedv) : Tac unit
let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h))
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 25, "end_line": 154, "start_col": 0, "start_line": 153 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
h: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.namedv", "FStar.Tactics.V2.Derived.exact", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Var", "Prims.unit" ]
[]
false
true
false
false
false
let exact_hyp' (h: namedv) : Tac unit =
exact (pack (Tv_Var h))
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.return
val return (#a: _) (x: a) : match_res a
val return (#a: _) (x: a) : match_res a
let return #a (x: a) : match_res a = Success x
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 11, "end_line": 248, "start_col": 0, "start_line": 247 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
x: a -> FStar.Tactics.PatternMatching.match_res a
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.PatternMatching.Success", "FStar.Tactics.PatternMatching.match_res" ]
[]
false
false
false
true
false
let return #a (x: a) : match_res a =
Success x
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.exact_hyp
val exact_hyp (a: Type0) (h: namedv) : Tac unit
val exact_hyp (a: Type0) (h: namedv) : Tac unit
let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 53, "end_line": 150, "start_col": 0, "start_line": 148 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
a: Type0 -> h: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.namedv", "FStar.Tactics.V2.Derived.exact", "FStar.Reflection.V2.Derived.mk_app", "Prims.Cons", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Pervasives.Native.Mktuple2", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Var", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Prims.Nil", "Prims.unit", "FStar.Squash.return_squash" ]
[]
false
true
false
false
false
let exact_hyp (a: Type0) (h: namedv) : Tac unit =
let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])
false
Hacl.Spec.SHA2.Lemmas.fst
Hacl.Spec.SHA2.Lemmas.transpose_state8_lemma
val transpose_state8_lemma: #a:sha2_alg -> #m:m_spec{lanes a m == 8} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in Seq.index (vec_v (transpose_state8 st).[ind / l]) (ind % l) == Seq.index (state_spec_v st).[j] (i / word_length a))
val transpose_state8_lemma: #a:sha2_alg -> #m:m_spec{lanes a m == 8} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in Seq.index (vec_v (transpose_state8 st).[ind / l]) (ind % l) == Seq.index (state_spec_v st).[j] (i / word_length a))
let transpose_state8_lemma #a #m st j i = let l = lanes a m in let ind = 8 * j + i / word_length a in let r0 = transpose8x8_lseq st in transpose8x8_lemma st
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 23, "end_line": 117, "start_col": 0, "start_line": 113 }
module Hacl.Spec.SHA2.Lemmas open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector open Lib.IntVector.Transpose open Spec.Hash.Definitions open Hacl.Spec.SHA2.Vec #set-options "--z3rlimit 50 --fuel 0 --ifuel 1" val transpose_ws4_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16 -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws4_lemma_ij #a #m ws j i = let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs); //assert ((transpose_ws4 ws).[i] == (sub (transpose_ws4 ws) (i_sub * l) l).[j_sub]); //assert ((transpose_ws4 ws).[i] == (transpose4x4_lseq vs).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v (transpose4x4_lseq vs).[j_sub]).[j]); transpose4x4_lemma vs; assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v vs.[j]).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i_sub * l + j]).[j_sub]) val transpose_ws8_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 8} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws8_lemma_ij #a #m ws j i = let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws8 ws) (i_sub * l) l) (transpose8x8_lseq vs); assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v (transpose8x8_lseq vs).[j_sub]).[j]); transpose8x8_lemma vs; assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i_sub * lanes a m + j]).[j_sub]) val transpose_ws_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws_lemma_ij #a #m ws j i = assert (((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v (transpose_ws ws).[i]).[j]); match lanes a m with | 1 -> () | 4 -> transpose_ws4_lemma_ij #a #m ws j i | 8 -> transpose_ws8_lemma_ij #a #m ws j i val transpose_state4_lemma: #a:sha2_alg -> #m:m_spec{lanes a m == 4} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in Seq.index (vec_v (transpose_state st).[ind / l]) (ind % l) == Seq.index (state_spec_v st).[j] (i / word_length a)) let transpose_state4_lemma #a #m st j i = let r0 = transpose4x4_lseq (sub st 0 4) in transpose4x4_lemma (sub st 0 4); let r1 = transpose4x4_lseq (sub st 4 4) in transpose4x4_lemma (sub st 4 4) val transpose_state8_lemma: #a:sha2_alg -> #m:m_spec{lanes a m == 8} -> st:state_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 8 * word_length a} -> Lemma (let l = lanes a m in let ind = 8 * j + i / word_length a in Seq.index (vec_v (transpose_state8 st).[ind / l]) (ind % l) == Seq.index (state_spec_v st).[j] (i / word_length a))
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.Transpose.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "Hacl.Spec.SHA2.Vec.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.SHA2.Lemmas.fst" }
[ { "abbrev": false, "full_module": "Hacl.Spec.SHA2.Vec", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector.Transpose", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "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": 1, "max_fuel": 0, "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
st: Hacl.Spec.SHA2.Vec.state_spec a m -> j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} -> i: Prims.nat{i < 8 * Spec.Hash.Definitions.word_length a} -> FStar.Pervasives.Lemma (ensures (let l = Hacl.Spec.SHA2.Vec.lanes a m in let ind = 8 * j + i / Spec.Hash.Definitions.word_length a in FStar.Seq.Base.index (Lib.IntVector.vec_v (Hacl.Spec.SHA2.Vec.transpose_state8 st).[ ind / l ]) (ind % l) == FStar.Seq.Base.index (Hacl.Spec.SHA2.Vec.state_spec_v st).[ j ] (i / Spec.Hash.Definitions.word_length a)))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Spec.Hash.Definitions.sha2_alg", "Hacl.Spec.SHA2.Vec.m_spec", "Prims.eq2", "Prims.int", "Hacl.Spec.SHA2.Vec.lanes", "Hacl.Spec.SHA2.Vec.state_spec", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "FStar.Mul.op_Star", "Spec.Hash.Definitions.word_length", "Lib.IntVector.Transpose.transpose8x8_lemma", "Spec.Hash.Definitions.word_t", "Lib.Sequence.lseq", "Lib.IntVector.vec_t", "Lib.IntVector.Transpose.transpose8x8_lseq", "Prims.op_Addition", "Prims.op_Division", "Hacl.Spec.SHA2.Vec.lanes_t", "Prims.unit" ]
[]
true
false
true
false
false
let transpose_state8_lemma #a #m st j i =
let l = lanes a m in let ind = 8 * j + i / word_length a in let r0 = transpose8x8_lseq st in transpose8x8_lemma st
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.raise
val raise (#a: _) (ex: match_exception) : match_res a
val raise (#a: _) (ex: match_exception) : match_res a
let raise #a (ex: match_exception) : match_res a = Failure ex
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 12, "end_line": 259, "start_col": 0, "start_line": 258 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
ex: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.PatternMatching.match_res a
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.PatternMatching.Failure", "FStar.Tactics.PatternMatching.match_res" ]
[]
false
false
false
true
false
let raise #a (ex: match_exception) : match_res a =
Failure ex
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.string_of_bindings
val string_of_bindings : bindings: FStar.Tactics.PatternMatching.bindings -> FStar.Tactics.Effect.Tac Prims.string
let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 27, "end_line": 287, "start_col": 0, "start_line": 284 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later.
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
bindings: FStar.Tactics.PatternMatching.bindings -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.bindings", "FStar.String.concat", "Prims.string", "Prims.list", "FStar.Tactics.Util.map", "FStar.Pervasives.Native.tuple2", "FStar.Stubs.Reflection.Types.term", "Prims.op_Hat", "FStar.Stubs.Tactics.V2.Builtins.term_to_string" ]
[]
false
true
false
false
false
let string_of_bindings (bindings: bindings) =
String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.interp_pattern
val interp_pattern: pat: pattern -> term -> Tac (match_res bindings)
val interp_pattern: pat: pattern -> term -> Tac (match_res bindings)
let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 43, "end_line": 328, "start_col": 0, "start_line": 325 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term.
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
pat: FStar.Tactics.PatternMatching.pattern -> _: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.match_res FStar.Tactics.PatternMatching.bindings)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.op_let_Question", "FStar.Tactics.PatternMatching.bindings", "Prims.list", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.return", "FStar.List.Tot.Base.rev", "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.interp_pattern_aux", "Prims.Nil" ]
[]
false
true
false
false
false
let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =
fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.absvar
val absvar : Type0
let absvar = binding
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 20, "end_line": 349, "start_col": 0, "start_line": 349 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// -----------
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
Type0
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.NamedView.binding" ]
[]
false
false
false
true
true
let absvar =
binding
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.string_of_matching_solution
val string_of_matching_solution : ms: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac Prims.string
let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }"
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 26, "end_line": 391, "start_col": 0, "start_line": 381 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
ms: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.matching_solution", "Prims.op_Hat", "Prims.string", "FStar.String.concat", "Prims.list", "FStar.Tactics.Util.map", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Derived.binding_to_string", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_hyps", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Tactics.V2.Builtins.term_to_string", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_vars" ]
[]
false
true
false
false
false
let string_of_matching_solution ms =
let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }"
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.ms_locate_var
val ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a
val ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a
let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 55, "end_line": 406, "start_col": 0, "start_line": 404 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
a: Type -> solution: FStar.Tactics.PatternMatching.matching_solution -> name: FStar.Tactics.PatternMatching.varname -> FStar.Tactics.Effect.Tac a
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.varname", "FStar.Stubs.Tactics.V2.Builtins.unquote", "FStar.Stubs.Reflection.Types.term", "FStar.Tactics.PatternMatching.assoc_varname_fail", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_vars" ]
[]
false
true
false
false
false
let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a =
unquote #a (assoc_varname_fail name solution.ms_vars)
false
IfcRulesReify.fst
IfcRulesReify.while_ni_com'_low_equiv_low
val while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ Low? l)) (ensures (ni_com' env (While e c v) l h0)) (decreases (decr_while (R?.l h0) (While e c v) + decr_while (R?.r h0) (While e c v)))
val while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ Low? l)) (ensures (ni_com' env (While e c v) l h0)) (decreases (decr_while (R?.l h0) (While e c v) + decr_while (R?.r h0) (While e c v)))
let rec while_ni_com'_low_equiv_low env e c v l h0 = let R h0l h0r = h0 in let v0l = reify (interpret_exp_st e) h0l in let v0r = reify (interpret_exp_st e) h0r in assert (v0l == v0r) ; if v0l = 0 then begin assert (interpret_com h0l (While e c v) == Some h0l); assert (interpret_com h0r (While e c v) == Some h0r) end else let m0l = interpret_exp' h0l v in let m0r = interpret_exp' h0r v in match reify (interpret_com_st c h0l) h0l with | None, _ -> interpret_while_nil e c v h0l | Some (), h2l -> match reify (interpret_com_st c h0r) h0r with | None, _ -> interpret_while_nil e c v h0r | Some (), h2r -> let m1l = interpret_exp' h2l v in let m1r = interpret_exp' h2r v in if m0l > m1l then if m0r > m1r then begin assert (decr_while h2l (While e c v) << decr_while h0l (While e c v)) ; while_ni_com'_low_equiv_low env e c v l (R h2l h2r) end else interpret_while_loops e c v h0r else interpret_while_loops e c v h0l
{ "file_name": "examples/rel/IfcRulesReify.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 44, "end_line": 500, "start_col": 0, "start_line": 473 }
(* Copyright 2008-2018 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 IfcRulesReify open Rel open WhileReify open FStar.DM4F.Heap.IntStoreFixed open FStar.DM4F.IntStoreExcFixed open FStar.Squash open FStar.Classical (****************************** Preliminaries ******************************) (* CH: Everything specialized to 2-point lattice *) type label = | Low | High val op_Less : label -> label -> Tot bool let op_Less l1 l2 = match l1, l2 with | Low,High -> true | _, _ -> false val op_Less_Equals : label -> label -> Tot bool let op_Less_Equals l1 l2 = match l1, l2 with | High,Low -> false | _, _ -> true val join : label -> label -> Tot label let join l1 l2 = match l1, l2 with | Low,Low -> Low | _, _ -> High val meet : label -> label -> Tot label let meet l1 l2 = match l1, l2 with | High, High -> High | _, _ -> Low let universal_property_meet l l1 l2 : Lemma (requires (l <= l1 /\ l <= l2)) (ensures (l <= meet l1 l2)) = () type label_fun = id -> Tot label type low_equiv (env:label_fun) (h1:rel heap) = (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x) (**************************** Typing Judgements ****************************) (* env |- e : l - Expressions do not modify the heap - Correctness - Low equivalent input heaps + Low label ==> same result *) let ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 = forall (h: rel heap). (* {:pattern (low_equiv env h)} *) (low_equiv env h /\ Low? l) ==> (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *) begin let vr = reify (interpret_exp_st e) (R?.r h)in let vl = reify (interpret_exp_st e) (R?.l h) in vr = vl end (* env,pc:l |- c - References with a label below l are not modified - Total correctness - Low equivalent input heaps ==> Low equivalent output heaps *) let inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0 = match interpret_com h0 c with | None -> True | Some h1 -> forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i let ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 = let R h0l h0r = h0 in (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *) (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *) (* begin match interpret_com h0l c, interpret_com h0r c with *) (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *) (* | _ -> True *) (* end *) begin match interpret_com h0l c with | Some h1l -> begin match interpret_com h0r c with | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r) | _ -> True end | _ -> True end let ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 = (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\ (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0) (*********************** Typing Rules for Expressions **********************) (* CH: The way we derive these rules looks more like a semantically-justified program logic than a syntactic type system. Any connection to Dave Naumann and Anindya Banerjee's "relational logic"? (e.g. https://arxiv.org/abs/1611.08992) *) (* Subtyping rule for expression labels E |- e : l1 l1 <= l2 ---------------------- E |- e : l2 *) val sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label -> Lemma (requires (l1 <= l2 /\ ni_exp env e l1)) (ensures (ni_exp env e l2)) let sub_exp _ _ _ _ = () (* Typing rule for dereferencing ---------------- E | - r : E(r) *) val avar_exp : env:label_fun -> r:id -> Lemma (ensures (ni_exp env (AVar r) (env r))) let avar_exp _ _ = () (* Typing rule for Int constants i : int ------- i : Low *) val aint_exp : env:label_fun -> i:int -> Lemma (requires True) (ensures (ni_exp env (AInt i) Low)) let aint_exp _ _ = () (* Typing rule for binary operators e1 : l e2 : l ---------------- e1 `op` e2 : l *) val binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label -> Lemma (requires (ni_exp env e1 l) /\ (ni_exp env e2 l)) (ensures (ni_exp env (AOp op e1 e2) l)) let binop_exp env op e1 e2 l = () (************************ Typing Rules for Commands ************************) (* Subtyping rule for commands env,pc:l1 |- c l2 <= l1 --------------------------- env,pc:l2 |- c *) val sub_com : env:label_fun -> c:com -> l1:label -> l2:label -> Lemma (requires (l2 <= l1 /\ ni_com env c l1 )) (ensures (ni_com env c l2 )) let sub_com _ _ _ _ = () (* Typing rule for assignment env |- e : env(r) ------------------------ env, pc:env(r) |- r := e - label of expression and context label have to be below label of r (first one to prevent explicit, second to prevent implicit flows) *) let assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap) : Lemma (ni_com' env (Assign r e) (env r) h0) = FStar.Squash.give_proof ne ; let vr = reify (interpret_exp_st e) (R?.r h0) in let vl = reify (interpret_exp_st e) (R?.l h0) in match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with | Some (), h1l -> begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\ h1r = upd (R?.r h0) r vr) | None, _ -> () end | None, _ -> () let assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap) : Lemma (inv_com' env (Assign r e) (env r) h0) = let v = reify (interpret_exp_st e) h0 in match reify (interpret_com_st (Assign r e) h0) h0 with | None, h1 -> () | Some (), h1 -> assert (h1 == upd h0 r v) val assign_com : env:label_fun -> e:exp -> r:id -> Lemma (requires (ni_exp env e (env r))) (ensures (ni_com env (Assign r e) (env r))) let assign_com env e r = forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ; forall_intro (assign_inv_com' env e r) let seq_nil1 (c1:com) (c2:com) (h:heap) : Lemma (requires (fst (reify (interpret_com_st c1 h) h) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None)) = () let seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap) : Lemma (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\ fst (reify (interpret_com_st c2 h1) h1) = None)) (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None)) = () (* Sequencing rule for commands env,pc:l |- c1 env,pc:l |- c2 ------------------------------ env,pc:l |- c1; c2 *) val seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (inv_com' env (Seq c1 c2) l h0)) let seq_inv_com' env c1 c2 l h0 = match reify (interpret_com_st c1 h0) h0 with | None, _ -> seq_nil1 c1 c2 h0 | Some (), h1 -> match reify (interpret_com_st c2 h1) h1 with | None, _ -> seq_nil2 c1 c2 h0 h1 | Some (), h2 -> () #set-options "--z3rlimit 50" let use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h}) : Lemma (requires ni_com env c l) (ensures (let R hl hr = h in match reify (interpret_com_st c hl) hl, reify (interpret_com_st c hr) hr with | (Some _, hl'), (Some _, hr') -> low_equiv env (R hl' hr') | _ -> True)) = () val seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com' env (Seq c1 c2) l h0)) let seq_com' env c1 c2 l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else begin assert (low_equiv env h0); let R h0l h0r = h0 in match reify (interpret_com_st c1 h0l) h0l with | None, _ -> seq_nil1 c1 c2 h0l | Some (), h1l -> match reify (interpret_com_st c1 h0r) h0r with | None, _ -> seq_nil1 c1 c2 h0r | Some (), h1r -> match reify (interpret_com_st c2 h1l) h1l with | None, _ -> seq_nil2 c1 c2 h0l h1l | Some (), h2l -> match reify (interpret_com_st c2 h1r) h1r with | None, _ -> seq_nil2 c1 c2 h0r h1r | Some (), h2r -> let h1 = R h1l h1r in use_ni_com env c1 l h0; assert (low_equiv env h1) ; let h2 = R h2l h2r in use_ni_com env c2 l h1; assert (low_equiv env h2) end val seq_com : env:label_fun -> c1:com -> c2:com -> l:label -> Lemma (requires (ni_com env c1 l /\ ni_com env c2 l)) (ensures (ni_com env (Seq c1 c2) l)) let seq_com env c1 c2 l = forall_intro (fun (h0:rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ; forall_intro (fun (h0:heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)) (* Typing rule for conditional commands env |- e : l env,pc:l |- ct env,pc:l |- cf ---------------------------------------------- env,pc:l |- if e <> 0 then ct else cf *) (* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *) val cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (inv_com' env (If e ct cf) l h0)) let cond_inv_com' env e ct cf l h0 = let v = reify (interpret_exp_st e) h0 in if v = 0 then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0) else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0) (* Works too but takes 20s more *) (* let c = if v = 0 then cf else ct in *) (* match reify (interpret_com_st c h0) h0 with *) (* | None, _ -> () *) (* | Some (), h1 -> () *) #reset-options "--max_fuel 1" let interpret_cond (e:exp) (ct:com) (cf:com) (h:heap) : Lemma (let v = reify (interpret_exp_st e) h in let c = if v = 0 then cf else ct in (reify (interpret_com_st (If e ct cf) h) h == reify (interpret_com_st c h) h)) = () val cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com' env (If e ct cf) l h0)) let cond_ni_com' env e ct cf l h0 = if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0)) then () else let R h0l h0r = h0 in let vl = reify (interpret_exp_st e) h0l in let vr = reify (interpret_exp_st e) h0r in if Low? l then begin assert (vl == vr) ; let c = if vl = 0 then cf else ct in assert (ni_com env c l) ; let cif = If e ct cf in //NS:05/15 ... this 2 should be trivial to prove. // Why do they require a lemma? interpret_cond e ct cf h0l; interpret_cond e ct cf h0r; use_ni_com env c l (R h0l h0r) end else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) match reify (interpret_com_st (If e ct cf) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (If e ct cf) h0r) h0r with | None, _ -> () | Some (), h1r -> cond_inv_com' env e ct cf l h0l ; cond_inv_com' env e ct cf l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) #set-options "--z3rlimit 5" val cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> Lemma (requires ((ni_exp env e l) /\ (ni_com env ct l) /\ (ni_com env cf l))) (ensures (ni_com env (If e ct cf) l)) let cond_com env e ct cf l = forall_intro (fun (h0:rel heap) -> cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ; forall_intro (fun (h0:heap) -> cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0)) (* Typing rule for Skip ------------------- env,pc:High |- skip *) val skip_com : env:label_fun -> Lemma (ni_com env Skip High) let skip_com _ = () (* While rule for commands env |- e : l env,pc:l |- c ----------------------------------- env,pc:l |- while (e <> 0) do c *) val while_inv_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l)) (ensures (inv_com' env (While e c v) l h0)) (decreases (decr_while h0 (While e c v))) #reset-options "--z3rlimit 40" let interpret_while_nil e c v h : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ fst (reify (interpret_com_st c h) h) == None)) (ensures (interpret_com h (While e c v) == None)) = () let interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap) : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\ (match reify (interpret_com_st c h) h with | None, _ -> True | Some _, h' -> interpret_exp' h' v >= interpret_exp' h v))) (ensures (interpret_com h (While e c v) == None)) = () let rec while_inv_com' env e c v l h0 = let v0 = reify (interpret_exp_st e) h0 in if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0) else let m0 = interpret_exp' h0 v in match reify (interpret_com_st c h0) h0 with | None, _ -> interpret_while_nil e c v h0 | Some (), h2 -> let m1 = interpret_exp' h2 v in if m0 > m1 then begin assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ; while_inv_com' env e c v l h2 end else interpret_while_loops e c v h0 val while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ High? l)) (ensures (ni_com' env (While e c v) l h0)) let while_ni_com'_low_equiv_high env e c v l h0 = (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *) let R h0l h0r = h0 in match reify (interpret_com_st (While e c v) h0l) h0l with | None, _ -> () | Some (), h1l -> match reify (interpret_com_st (While e c v) h0r) h0r with | None, _ -> () | Some (), h1r -> while_inv_com' env e c v l h0l ; while_inv_com' env e c v l h0r ; assert (low_equiv env h0 ==> low_equiv env (R h1l h1r)) val while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap -> Lemma (requires (ni_exp env e l /\ ni_com env c l /\ low_equiv env h0 /\ Low? l)) (ensures (ni_com' env (While e c v) l h0))
{ "checked_file": "/", "dependencies": [ "WhileReify.fst.checked", "Rel.fst.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.DM4F.IntStoreExcFixed.fst.checked", "FStar.DM4F.Heap.IntStoreFixed.fsti.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "IfcRulesReify.fst" }
[ { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "FStar.Squash", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.IntStoreExcFixed", "short_module": null }, { "abbrev": false, "full_module": "FStar.DM4F.Heap.IntStoreFixed", "short_module": null }, { "abbrev": false, "full_module": "WhileReify", "short_module": null }, { "abbrev": false, "full_module": "Rel", "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": 40, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
env: IfcRulesReify.label_fun -> e: WhileReify.exp -> c: WhileReify.com -> v: WhileReify.metric -> l: IfcRulesReify.label -> h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\ IfcRulesReify.ni_com env c l /\ IfcRulesReify.low_equiv env h0 /\ Low? l) (ensures IfcRulesReify.ni_com' env (WhileReify.While e c v) l h0) (decreases WhileReify.decr_while (R?.l h0) (WhileReify.While e c v) + WhileReify.decr_while (R?.r h0) (WhileReify.While e c v))
FStar.Pervasives.Lemma
[ "lemma", "" ]
[]
[ "IfcRulesReify.label_fun", "WhileReify.exp", "WhileReify.com", "WhileReify.metric", "IfcRulesReify.label", "Rel.rel", "FStar.DM4F.Heap.IntStoreFixed.heap", "Prims.op_Equality", "Prims.int", "Prims._assert", "Prims.eq2", "FStar.Pervasives.Native.option", "WhileReify.interpret_com", "WhileReify.While", "FStar.Pervasives.Native.Some", "Prims.unit", "Prims.bool", "WhileReify.interpret_com_st", "IfcRulesReify.interpret_while_nil", "Prims.op_GreaterThan", "IfcRulesReify.while_ni_com'_low_equiv_low", "Rel.R", "Prims.precedes", "Prims.nat", "WhileReify.decr_while", "IfcRulesReify.interpret_while_loops", "WhileReify.interpret_exp'", "WhileReify.interpret_exp_st" ]
[ "recursion" ]
false
false
true
false
false
let rec while_ni_com'_low_equiv_low env e c v l h0 =
let R h0l h0r = h0 in let v0l = reify (interpret_exp_st e) h0l in let v0r = reify (interpret_exp_st e) h0r in assert (v0l == v0r); if v0l = 0 then (assert (interpret_com h0l (While e c v) == Some h0l); assert (interpret_com h0r (While e c v) == Some h0r)) else let m0l = interpret_exp' h0l v in let m0r = interpret_exp' h0r v in match reify (interpret_com_st c h0l) h0l with | None, _ -> interpret_while_nil e c v h0l | Some (), h2l -> match reify (interpret_com_st c h0r) h0r with | None, _ -> interpret_while_nil e c v h0r | Some (), h2r -> let m1l = interpret_exp' h2l v in let m1r = interpret_exp' h2r v in if m0l > m1l then if m0r > m1r then (assert (decr_while h2l (While e c v) << decr_while h0l (While e c v)); while_ni_com'_low_equiv_low env e c v l (R h2l h2r)) else interpret_while_loops e c v h0r else interpret_while_loops e c v h0l
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.ms_locate_hyp
val ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis
val ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis
let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 42, "end_line": 402, "start_col": 0, "start_line": 400 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
a: Type -> solution: FStar.Tactics.PatternMatching.matching_solution -> name: FStar.Tactics.PatternMatching.varname -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.hypothesis
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.assoc_varname_fail", "FStar.Tactics.PatternMatching.hypothesis", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_hyps" ]
[]
false
true
false
false
false
let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis =
assoc_varname_fail name solution.ms_hyps
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.hyp_qn
val hyp_qn : Prims.string
let hyp_qn = `%hyp
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 19, "end_line": 562, "start_col": 0, "start_line": 562 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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.string
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
false
let hyp_qn =
`%hyp
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.goal_qn
val goal_qn : Prims.string
let goal_qn = `%pm_goal
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 23, "end_line": 563, "start_col": 0, "start_line": 563 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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.string
Prims.Tot
[ "total" ]
[]
[]
[]
false
false
false
true
false
let goal_qn =
`%pm_goal
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.pm_goal
val pm_goal : a: Type -> Prims.eqtype
let pm_goal (a: Type) = unit
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 28, "end_line": 560, "start_col": 0, "start_line": 560 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
a: Type -> Prims.eqtype
Prims.Tot
[ "total" ]
[]
[ "Prims.unit", "Prims.eqtype" ]
[]
false
false
false
true
false
let pm_goal (a: Type) =
unit
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.name_of_namedv
val name_of_namedv (x: namedv) : Tac string
val name_of_namedv (x: namedv) : Tac string
let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 34, "end_line": 504, "start_col": 0, "start_line": 503 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns.
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
x: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.namedv", "FStar.Tactics.Unseal.unseal", "Prims.string", "FStar.Stubs.Reflection.V2.Data.__proj__Mknamedv_view__item__ppname", "FStar.Tactics.NamedView.inspect_namedv" ]
[]
false
true
false
false
false
let name_of_namedv (x: namedv) : Tac string =
unseal (inspect_namedv x).ppname
false
MerkleTree.Spec.fst
MerkleTree.Spec.hashes
val hashes (#hsz:pos): Type0
val hashes (#hsz:pos): Type0
let hashes #hsz = S.seq (padded_hash #hsz)
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "7d7bdc20f2033171e279c176b26e84f9069d23c6", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
{ "end_col": 42, "end_line": 46, "start_col": 0, "start_line": 46 }
module MerkleTree.Spec open FStar.Classical open FStar.Mul open FStar.Seq module S = FStar.Seq #set-options "--max_fuel 0 --max_ifuel 0 --z3rlimit 10" // For SHA2_256, this is is a sequence of 32 bytes // These are secret bytes, hence not an eqtype type hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz } type hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz) val sha256_compress: hash_fun_t #32 let sha256_compress src1 src2 = let sz = Spec.Hash.Definitions.SHA2_256 in let hash_alg = Spec.Hash.Definitions.SHA2_256 in let acc = Spec.Agile.Hash.init hash_alg in let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in Spec.Agile.Hash.finish hash_alg acc () /// For simplicity, we will specify the root for a sequence of [i] /// tags where [i <= 2^n] as the root of a full binary tree with [2^n] /// leaves obtained by padding the sequence with dummies. This /// requires extending the definitions of hashes and hash functions. Our /// extended definition of hash justifies skipping any concrete /// computation on dummies. noeq type padded_hash #hsz = | HRaw: hr:hash #hsz -> padded_hash #hsz | HPad // right padding to make the size of a Merkle tree a power of 2 val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz) let padded_hash_fun #hsz f lh rh = allow_inversion (padded_hash #hsz); match lh, rh with | HPad , _ -> HPad | _ , HPad -> lh | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr) noextract
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "Spec.Agile.Hash.fsti.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "MerkleTree.Spec.fst" }
[ { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Seq", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "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": 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": 10, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
Type0
Prims.Tot
[ "total" ]
[]
[ "Prims.pos", "FStar.Seq.Base.seq", "MerkleTree.Spec.padded_hash" ]
[]
false
false
false
true
true
let hashes #hsz =
S.seq (padded_hash #hsz)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.hyp
val hyp : a: Type -> Type0
let hyp (a: Type) = binding
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 27, "end_line": 559, "start_col": 0, "start_line": 559 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization.
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
a: Type -> Type0
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.NamedView.binding" ]
[]
false
false
false
true
true
let hyp (a: Type) =
binding
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.type_of_named_binder
val type_of_named_binder (nb: binder) : term
val type_of_named_binder (nb: binder) : term
let type_of_named_binder (nb : binder) : term = nb.sort
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 8, "end_line": 585, "start_col": 0, "start_line": 584 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
nb: FStar.Tactics.NamedView.binder -> FStar.Tactics.NamedView.term
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.NamedView.binder", "FStar.Tactics.NamedView.__proj__Mkbinder__item__sort", "FStar.Tactics.NamedView.term" ]
[]
false
false
false
true
false
let type_of_named_binder (nb: binder) : term =
nb.sort
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.beta_reduce
val beta_reduce (tm: term) : Tac term
val beta_reduce (tm: term) : Tac term
let beta_reduce (tm: term) : Tac term = norm_term [] tm
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 17, "end_line": 527, "start_col": 0, "start_line": 526 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
tm: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Tactics.V2.Derived.norm_term", "Prims.Nil", "FStar.Pervasives.norm_step" ]
[]
false
true
false
false
false
let beta_reduce (tm: term) : Tac term =
norm_term [] tm
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.cleanup_abspat
val cleanup_abspat (t: term) : Tac term
val cleanup_abspat (t: term) : Tac term
let cleanup_abspat (t: term) : Tac term = norm_term [] t
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 16, "end_line": 611, "start_col": 0, "start_line": 610 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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.Tactics.NamedView.term
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.term", "FStar.Tactics.V2.Derived.norm_term", "Prims.Nil", "FStar.Pervasives.norm_step" ]
[]
false
true
false
false
false
let cleanup_abspat (t: term) : Tac term =
norm_term [] t
false
Hacl.Spec.SHA2.Lemmas.fst
Hacl.Spec.SHA2.Lemmas.transpose_ws4_lemma_ij
val transpose_ws4_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16 -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])
val transpose_ws4_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16 -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])
let transpose_ws4_lemma_ij #a #m ws j i = let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs); //assert ((transpose_ws4 ws).[i] == (sub (transpose_ws4 ws) (i_sub * l) l).[j_sub]); //assert ((transpose_ws4 ws).[i] == (transpose4x4_lseq vs).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v (transpose4x4_lseq vs).[j_sub]).[j]); transpose4x4_lemma vs; assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v vs.[j]).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i_sub * l + j]).[j_sub])
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 83, "end_line": 38, "start_col": 0, "start_line": 25 }
module Hacl.Spec.SHA2.Lemmas open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector open Lib.IntVector.Transpose open Spec.Hash.Definitions open Hacl.Spec.SHA2.Vec #set-options "--z3rlimit 50 --fuel 0 --ifuel 1" val transpose_ws4_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16 -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.Transpose.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "Hacl.Spec.SHA2.Vec.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.SHA2.Lemmas.fst" }
[ { "abbrev": false, "full_module": "Hacl.Spec.SHA2.Vec", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector.Transpose", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "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": 1, "max_fuel": 0, "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
ws: Hacl.Spec.SHA2.Vec.ws_spec a m -> j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} -> i: Prims.nat{i < 16} -> FStar.Pervasives.Lemma (ensures (let l = Hacl.Spec.SHA2.Vec.lanes a m in (Lib.IntVector.vec_v (Hacl.Spec.SHA2.Vec.transpose_ws4 ws).[ i ]).[ j ] == (Lib.IntVector.vec_v ws.[ (i / l) * l + j ]).[ i % l ]))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Spec.Hash.Definitions.sha2_alg", "Hacl.Spec.SHA2.Vec.m_spec", "Prims.eq2", "Prims.int", "Hacl.Spec.SHA2.Vec.lanes", "Hacl.Spec.SHA2.Vec.ws_spec", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "Prims._assert", "Lib.IntTypes.uint_t", "Spec.Hash.Definitions.word_t", "Lib.IntTypes.SEC", "Prims.l_or", "FStar.Seq.Base.index", "Lib.Sequence.to_seq", "Lib.IntVector.vec_v", "Lib.Sequence.op_String_Access", "Hacl.Spec.SHA2.Vec.element_t", "Prims.op_Addition", "FStar.Mul.op_Star", "Hacl.Spec.SHA2.Vec.transpose_ws4", "Prims.unit", "Lib.IntVector.Transpose.transpose4x4_lemma", "Lib.IntVector.vec_t", "Lib.IntVector.Transpose.transpose4x4_lseq", "Lib.Sequence.eq_intro", "Lib.Sequence.sub", "Lib.Sequence.lseq", "Prims.l_and", "FStar.Seq.Base.seq", "FStar.Seq.Base.slice", "Prims.op_Multiply", "Prims.l_Forall", "Lib.Sequence.index", "Prims.op_Modulus", "Prims.op_Division", "Hacl.Spec.SHA2.Vec.lanes_t" ]
[]
true
false
true
false
false
let transpose_ws4_lemma_ij #a #m ws j i =
let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs); assert ((vec_v (transpose_ws4 ws).[ i ]).[ j ] == (vec_v (transpose4x4_lseq vs).[ j_sub ]).[ j ]); transpose4x4_lemma vs; assert ((vec_v (transpose_ws4 ws).[ i ]).[ j ] == (vec_v vs.[ j ]).[ j_sub ]); assert ((vec_v (transpose_ws4 ws).[ i ]).[ j ] == (vec_v ws.[ i_sub * l + j ]).[ j_sub ])
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.name_of_named_binder
val name_of_named_binder (nb: binder) : Tac string
val name_of_named_binder (nb: binder) : Tac string
let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 17, "end_line": 615, "start_col": 0, "start_line": 614 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
nb: FStar.Tactics.NamedView.binder -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.NamedView.binder", "FStar.Tactics.Unseal.unseal", "Prims.string", "FStar.Tactics.NamedView.__proj__Mkbinder__item__ppname" ]
[]
false
true
false
false
false
let name_of_named_binder (nb: binder) : Tac string =
unseal nb.ppname
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.specialize_abspat_continuation'
val specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term) : Tac term
val specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term) : Tac term
let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) []
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 52, "end_line": 733, "start_col": 0, "start_line": 727 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
continuation: FStar.Tactics.PatternMatching.abspat_continuation -> solution_term: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Tactics.PatternMatching.abspat_argspec", "FStar.Tactics.PatternMatching.hoist_and_apply", "Prims.Nil", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Tactics.Util.map", "FStar.Tactics.PatternMatching.abspat_arg_of_abspat_argspec" ]
[]
false
true
false
false
false
let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term) : Tac term =
let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) []
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.interp_abspat_continuation
val interp_abspat_continuation (a: Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a)
val interp_abspat_continuation (a: Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a)
let interp_abspat_continuation (a:Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a) = let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 47, "end_line": 755, "start_col": 0, "start_line": 752 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args))) let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) [] (** Specialize a continuation of type ``abspat_continuation``. This yields a quoted function taking a matching solution and running its body with appropriate bindings. **) let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term = let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("… which reduces to " ^ (term_to_string normalized)); thunked (** Interpret a continuation of type ``abspat_continuation``. This yields a function taking a matching solution and running the body of the
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
a: Type0 -> continuation: FStar.Tactics.PatternMatching.abspat_continuation -> FStar.Tactics.Effect.Tac (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Stubs.Tactics.V2.Builtins.unquote", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.specialize_abspat_continuation" ]
[]
false
true
false
false
false
let interp_abspat_continuation (a: Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a) =
let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied
false
MerkleTree.Spec.fst
MerkleTree.Spec.op_String_Access
val op_String_Access : s: FStar.Seq.Base.seq MerkleTree.Spec.padded_hash -> i: Prims.nat{i < FStar.Seq.Base.length s} -> MerkleTree.Spec.padded_hash
let op_String_Access (#hsz:pos) = S.index #(padded_hash #hsz)
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "7d7bdc20f2033171e279c176b26e84f9069d23c6", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
{ "end_col": 68, "end_line": 53, "start_col": 7, "start_line": 53 }
module MerkleTree.Spec open FStar.Classical open FStar.Mul open FStar.Seq module S = FStar.Seq #set-options "--max_fuel 0 --max_ifuel 0 --z3rlimit 10" // For SHA2_256, this is is a sequence of 32 bytes // These are secret bytes, hence not an eqtype type hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz } type hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz) val sha256_compress: hash_fun_t #32 let sha256_compress src1 src2 = let sz = Spec.Hash.Definitions.SHA2_256 in let hash_alg = Spec.Hash.Definitions.SHA2_256 in let acc = Spec.Agile.Hash.init hash_alg in let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in Spec.Agile.Hash.finish hash_alg acc () /// For simplicity, we will specify the root for a sequence of [i] /// tags where [i <= 2^n] as the root of a full binary tree with [2^n] /// leaves obtained by padding the sequence with dummies. This /// requires extending the definitions of hashes and hash functions. Our /// extended definition of hash justifies skipping any concrete /// computation on dummies. noeq type padded_hash #hsz = | HRaw: hr:hash #hsz -> padded_hash #hsz | HPad // right padding to make the size of a Merkle tree a power of 2 val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz) let padded_hash_fun #hsz f lh rh = allow_inversion (padded_hash #hsz); match lh, rh with | HPad , _ -> HPad | _ , HPad -> lh | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr) noextract val hashes (#hsz:pos): Type0 let hashes #hsz = S.seq (padded_hash #hsz) type merkle_tree (#hsz:pos) n = hs:hashes #hsz {S.length hs = pow2 n} val mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz) let mt_get #_ #_ mt idx = S.index mt idx
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "Spec.Agile.Hash.fsti.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "MerkleTree.Spec.fst" }
[ { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Seq", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "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": 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": 10, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
s: FStar.Seq.Base.seq MerkleTree.Spec.padded_hash -> i: Prims.nat{i < FStar.Seq.Base.length s} -> MerkleTree.Spec.padded_hash
Prims.Tot
[ "total" ]
[]
[ "Prims.pos", "FStar.Seq.Base.index", "MerkleTree.Spec.padded_hash", "FStar.Seq.Base.seq", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "FStar.Seq.Base.length" ]
[]
false
false
false
false
false
let ( .[] ) (#hsz: pos) =
S.index #(padded_hash #hsz)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.inspect_abspat_solution
val inspect_abspat_solution (#a: _) (abspat: a) : Tac matching_solution
val inspect_abspat_solution (#a: _) (abspat: a) : Tac matching_solution
let inspect_abspat_solution #a (abspat: a) : Tac matching_solution = match_abspat abspat (fun _ -> (fun solution -> solution <: Tac _) <: Tac _)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 77, "end_line": 784, "start_col": 0, "start_line": 783 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args))) let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) [] (** Specialize a continuation of type ``abspat_continuation``. This yields a quoted function taking a matching solution and running its body with appropriate bindings. **) let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term = let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("… which reduces to " ^ (term_to_string normalized)); thunked (** Interpret a continuation of type ``abspat_continuation``. This yields a function taking a matching solution and running the body of the continuation with appropriate bindings. **) let interp_abspat_continuation (a:Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a) = let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied /// Putting it all together /// ======================= /// /// We now have all we need to use pattern-matching, short of a few convenience functions: (** Construct a matching problem from an abspat. **) let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) = matching_problem_of_abs (quote abspat) (** Construct an solve a matching problem. This higher-order function isn't very usable on its own — it's mostly a convenience function to avoid duplicating the problem-parsing code. **) let match_abspat #b #a (abspat: a) (k: abspat_continuation -> Tac (matching_solution -> Tac b)) : Tac b = let goal = cur_goal () in let hypotheses = vars_of_env (cur_env ()) in let problem, continuation = interp_abspat abspat in solve_mp problem hypotheses goal (k continuation) (** Inspect the matching problem produced by parsing an abspat. **) let inspect_abspat_problem #a (abspat: a) : Tac matching_problem = fst (interp_abspat #a abspat)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
abspat: a -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.matching_solution
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.match_abspat", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.abspat_continuation" ]
[]
false
true
false
false
false
let inspect_abspat_solution #a (abspat: a) : Tac matching_solution =
match_abspat abspat (fun _ -> (fun solution -> solution <: Tac _) <: Tac _)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.specialize_abspat_continuation
val specialize_abspat_continuation (continuation: abspat_continuation) : Tac term
val specialize_abspat_continuation (continuation: abspat_continuation) : Tac term
let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term = let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("… which reduces to " ^ (term_to_string normalized)); thunked
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 9, "end_line": 747, "start_col": 0, "start_line": 738 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args))) let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) [] (** Specialize a continuation of type ``abspat_continuation``. This yields a quoted function taking a matching solution and running its body with appropriate
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
continuation: FStar.Tactics.PatternMatching.abspat_continuation -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Tactics.NamedView.term", "Prims.unit", "FStar.Tactics.PatternMatching.debug", "Prims.string", "Prims.op_Hat", "FStar.Stubs.Tactics.V2.Builtins.term_to_string", "FStar.Tactics.PatternMatching.beta_reduce", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Abs", "FStar.Tactics.PatternMatching.specialize_abspat_continuation'", "FStar.Tactics.NamedView.Tv_Var", "FStar.Tactics.V2.SyntaxCoercions.binder_to_namedv", "FStar.Tactics.NamedView.simple_binder", "FStar.Tactics.V2.Derived.fresh_binder" ]
[]
false
true
false
false
false
let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term =
let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("\226\128\166 which reduces to " ^ (term_to_string normalized)); thunked
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.desc_of_pattern
val desc_of_pattern : _: FStar.Tactics.PatternMatching.pattern -> Prims.string
let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application"
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 38, "end_line": 176, "start_col": 0, "start_line": 172 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
_: FStar.Tactics.PatternMatching.pattern -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.qn", "Prims.op_Hat", "Prims.string" ]
[]
false
false
false
true
false
let desc_of_pattern =
function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application"
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.inspect_abspat_problem
val inspect_abspat_problem (#a: _) (abspat: a) : Tac matching_problem
val inspect_abspat_problem (#a: _) (abspat: a) : Tac matching_problem
let inspect_abspat_problem #a (abspat: a) : Tac matching_problem = fst (interp_abspat #a abspat)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 31, "end_line": 780, "start_col": 0, "start_line": 779 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args))) let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) [] (** Specialize a continuation of type ``abspat_continuation``. This yields a quoted function taking a matching solution and running its body with appropriate bindings. **) let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term = let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("… which reduces to " ^ (term_to_string normalized)); thunked (** Interpret a continuation of type ``abspat_continuation``. This yields a function taking a matching solution and running the body of the continuation with appropriate bindings. **) let interp_abspat_continuation (a:Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a) = let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied /// Putting it all together /// ======================= /// /// We now have all we need to use pattern-matching, short of a few convenience functions: (** Construct a matching problem from an abspat. **) let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) = matching_problem_of_abs (quote abspat) (** Construct an solve a matching problem. This higher-order function isn't very usable on its own — it's mostly a convenience function to avoid duplicating the problem-parsing code. **) let match_abspat #b #a (abspat: a) (k: abspat_continuation -> Tac (matching_solution -> Tac b)) : Tac b = let goal = cur_goal () in let hypotheses = vars_of_env (cur_env ()) in let problem, continuation = interp_abspat abspat in solve_mp problem hypotheses goal (k continuation)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
abspat: a -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.matching_problem
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Pervasives.Native.fst", "FStar.Tactics.PatternMatching.matching_problem", "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.interp_abspat" ]
[]
false
true
false
false
false
let inspect_abspat_problem #a (abspat: a) : Tac matching_problem =
fst (interp_abspat #a abspat)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.tpair
val tpair (#a #b: _) (x: a) : Tac (b -> Tac (a * b))
val tpair (#a #b: _) (x: a) : Tac (b -> Tac (a * b))
let tpair #a #b (x : a) : Tac (b -> Tac (a * b)) = fun (y: b) -> (x, y)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 22, "end_line": 787, "start_col": 0, "start_line": 786 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args))) let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) [] (** Specialize a continuation of type ``abspat_continuation``. This yields a quoted function taking a matching solution and running its body with appropriate bindings. **) let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term = let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("… which reduces to " ^ (term_to_string normalized)); thunked (** Interpret a continuation of type ``abspat_continuation``. This yields a function taking a matching solution and running the body of the continuation with appropriate bindings. **) let interp_abspat_continuation (a:Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a) = let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied /// Putting it all together /// ======================= /// /// We now have all we need to use pattern-matching, short of a few convenience functions: (** Construct a matching problem from an abspat. **) let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) = matching_problem_of_abs (quote abspat) (** Construct an solve a matching problem. This higher-order function isn't very usable on its own — it's mostly a convenience function to avoid duplicating the problem-parsing code. **) let match_abspat #b #a (abspat: a) (k: abspat_continuation -> Tac (matching_solution -> Tac b)) : Tac b = let goal = cur_goal () in let hypotheses = vars_of_env (cur_env ()) in let problem, continuation = interp_abspat abspat in solve_mp problem hypotheses goal (k continuation) (** Inspect the matching problem produced by parsing an abspat. **) let inspect_abspat_problem #a (abspat: a) : Tac matching_problem = fst (interp_abspat #a abspat) (** Inspect the matching solution produced by parsing and solving an abspat. **) let inspect_abspat_solution #a (abspat: a) : Tac matching_solution = match_abspat abspat (fun _ -> (fun solution -> solution <: Tac _) <: Tac _)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
x: a -> FStar.Tactics.Effect.Tac (_: b -> FStar.Tactics.Effect.Tac (a * b))
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.tuple2" ]
[]
false
true
false
false
false
let tpair #a #b (x: a) : Tac (b -> Tac (a * b)) =
fun (y: b) -> (x, y)
false
Pulse.Checker.IntroPure.fst
Pulse.Checker.IntroPure.check_prop
val check_prop (g: env) (p: term) : T.Tac (p: term & tot_typing g p tm_prop)
val check_prop (g: env) (p: term) : T.Tac (p: term & tot_typing g p tm_prop)
let check_prop (g:env) (p:term) : T.Tac (p:term & tot_typing g p tm_prop) = let p0 = p in let (| p, p_typing |) = Pulse.Checker.Pure.check_vprop g (tm_pure p) in match p.t with | Tm_Pure pp -> let prop_typing = Pulse.Typing.Metatheory.pure_typing_inversion #_ #pp p_typing in (| pp, prop_typing |) | _ -> fail g None (Printf.sprintf "Impossible: check_intro_pure: checking a pure vprop %s returned a non-pure vprop %s,\ please file a bug-report" (P.term_to_string (tm_pure p0)) (P.term_to_string p))
{ "file_name": "lib/steel/pulse/Pulse.Checker.IntroPure.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 30, "end_line": 41, "start_col": 0, "start_line": 27 }
(* Copyright 2023 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 Pulse.Checker.IntroPure open Pulse.Syntax open Pulse.Typing open Pulse.Checker.Base open Pulse.Checker.Prover module T = FStar.Tactics.V2 module P = Pulse.Syntax.Printer
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.Metatheory.fsti.checked", "Pulse.Typing.Env.fsti.checked", "Pulse.Typing.fst.checked", "Pulse.Syntax.Printer.fsti.checked", "Pulse.Syntax.fst.checked", "Pulse.Checker.Pure.fsti.checked", "Pulse.Checker.Prover.fsti.checked", "Pulse.Checker.Base.fsti.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Printf.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": true, "source_file": "Pulse.Checker.IntroPure.fst" }
[ { "abbrev": true, "full_module": "Pulse.Syntax.Printer", "short_module": "P" }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "Pulse.Checker.Prover", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker.Base", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": false, "full_module": "Pulse.Checker.Base", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Checker", "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: Pulse.Typing.Env.env -> p: Pulse.Syntax.Base.term -> FStar.Tactics.Effect.Tac (Prims.dtuple2 Pulse.Syntax.Base.term (fun p -> Pulse.Typing.tot_typing g p Pulse.Typing.tm_prop))
FStar.Tactics.Effect.Tac
[]
[]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.term", "Pulse.Typing.tot_typing", "Pulse.Syntax.Base.tm_vprop", "Pulse.Syntax.Base.__proj__Mkterm__item__t", "Prims.Mkdtuple2", "Pulse.Typing.tm_prop", "Pulse.Syntax.Base.tm_fstar", "FStar.Reflection.Typing.tm_prop", "FStar.Range.range_0", "Pulse.Typing.Metatheory.Base.pure_typing_inversion", "Prims.dtuple2", "Pulse.Syntax.Base.term'", "Pulse.Typing.Env.fail", "FStar.Pervasives.Native.None", "Pulse.Syntax.Base.range", "Prims.string", "FStar.Printf.sprintf", "Pulse.Syntax.Printer.term_to_string", "Pulse.Syntax.Base.tm_pure", "Pulse.Checker.Pure.check_vprop" ]
[]
false
true
false
false
false
let check_prop (g: env) (p: term) : T.Tac (p: term & tot_typing g p tm_prop) =
let p0 = p in let (| p , p_typing |) = Pulse.Checker.Pure.check_vprop g (tm_pure p) in match p.t with | Tm_Pure pp -> let prop_typing = Pulse.Typing.Metatheory.pure_typing_inversion #_ #pp p_typing in (| pp, prop_typing |) | _ -> fail g None (Printf.sprintf "Impossible: check_intro_pure: checking a pure vprop %s returned a non-pure vprop %s,please file a bug-report" (P.term_to_string (tm_pure p0)) (P.term_to_string p))
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.interp_abspat
val interp_abspat (#a: _) (abspat: a) : Tac (matching_problem * abspat_continuation)
val interp_abspat (#a: _) (abspat: a) : Tac (matching_problem * abspat_continuation)
let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) = matching_problem_of_abs (quote abspat)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 40, "end_line": 765, "start_col": 0, "start_line": 763 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args))) let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) [] (** Specialize a continuation of type ``abspat_continuation``. This yields a quoted function taking a matching solution and running its body with appropriate bindings. **) let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term = let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("… which reduces to " ^ (term_to_string normalized)); thunked (** Interpret a continuation of type ``abspat_continuation``. This yields a function taking a matching solution and running the body of the continuation with appropriate bindings. **) let interp_abspat_continuation (a:Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a) = let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied /// Putting it all together /// ======================= /// /// We now have all we need to use pattern-matching, short of a few convenience functions:
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
abspat: a -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.matching_problem * FStar.Tactics.PatternMatching.abspat_continuation)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.matching_problem_of_abs", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.matching_problem", "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.Types.term" ]
[]
false
true
false
false
false
let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) =
matching_problem_of_abs (quote abspat)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.string_of_pattern
val string_of_pattern : _: FStar.Tactics.PatternMatching.pattern -> Prims.string
let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")"
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 44, "end_line": 183, "start_col": 0, "start_line": 178 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
_: FStar.Tactics.PatternMatching.pattern -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.varname", "Prims.op_Hat", "FStar.Tactics.PatternMatching.qn", "FStar.Tactics.PatternMatching.string_of_pattern", "Prims.string" ]
[ "recursion" ]
false
false
false
true
false
let rec string_of_pattern =
function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")"
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_br
val elab_br (#g: env) (#c: comp_st) (#sc_u: universe) (#sc_ty: typ) (#sc: term) (#p: pattern) (#e: st_term) (d: br_typing g sc_u sc_ty sc p e c) : Tot R.branch (decreases d)
val elab_br (#g: env) (#c: comp_st) (#sc_u: universe) (#sc_ty: typ) (#sc: term) (#p: pattern) (#e: st_term) (d: br_typing g sc_u sc_ty sc p e c) : Tot R.branch (decreases d)
let rec elab_st_typing (#g:env) (#t:st_term) (#c:comp) (d:st_typing g t c) : Tot R.term (decreases d) = match d with // | T_Tot _ t _ _ -> elab_term t | T_Abs _ x qual b _u body _c ty_typing body_typing -> let ty = elab_term b.binder_ty in let ppname = b.binder_ppname.name in let body = elab_st_typing body_typing in mk_abs_with_name ppname ty (elab_qual qual) (RT.close_term body x) //this closure should be provably redundant by strengthening the conditions on x | T_STApp _ head _ qual _ arg _ _ | T_STGhostApp _ head _ qual _ arg _ _ _ _ -> let head = elab_term head in let arg = elab_term arg in R.mk_app head [(arg, elab_qual qual)] | T_Return _ c use_eq u ty t post _ _ _ _ -> let ru = u in let rty = elab_term ty in let rt = elab_term t in let rp = elab_term post in let rp = mk_abs rty R.Q_Explicit rp in (match c, use_eq with | STT, true -> mk_stt_return ru rty rt rp | STT, false -> mk_stt_return_noeq ru rty rt rp | STT_Atomic, true -> mk_stt_atomic_return ru rty rt rp | STT_Atomic, false -> mk_stt_atomic_return_noeq ru rty rt rp | STT_Ghost, true -> mk_stt_ghost_return ru rty rt rp | STT_Ghost, false -> mk_stt_ghost_return_noeq ru rty rt rp) | T_Bind _ e1 e2 c1 c2 b x c e1_typing t_typing e2_typing bc -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in elab_bind bc e1 (mk_abs_with_name b.binder_ppname.name ty1 R.Q_Explicit (RT.close_term e2 x)) | T_BindFn _ _ _ c1 c2 b x e1_typing _u t_typing e2_typing c2_typing -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in RT.mk_let RT.pp_name_default e1 ty1 (RT.close_term e2 x) | T_Frame _ _ c frame _frame_typing e_typing -> let e = elab_st_typing e_typing in elab_frame c frame e | T_Equiv _ _ c1 c2 e_typing (ST_TotEquiv _ _ _ _ _ _) -> let e = elab_st_typing e_typing in e | T_Equiv _ _ c1 c2 e_typing _ -> let e = elab_st_typing e_typing in elab_sub c1 c2 e | T_Sub _ _ c1 c2 e_typing d_sub -> let e = elab_st_typing e_typing in let (| coercion, _ |) = elab_st_sub d_sub in R.mk_e_app coercion [e] | T_Lift _ _ c1 c2 e_typing lc -> let e = elab_st_typing e_typing in elab_lift lc e | T_If _ b _ _ _ _ _ e1_typing e2_typing _c_typing -> let rb = elab_term b in let re1 = elab_st_typing e1_typing in let re2 = elab_st_typing e2_typing in RT.mk_if rb re1 re2 | T_Match _ _ _ sc _ _ _ _ _ brty _ -> let sc = elab_term sc in let brs = elab_branches brty in R.pack_ln (R.Tv_Match sc None brs) | T_IntroPure _ p _ _ -> let head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p in let arg = (`()) in R.mk_app (elab_term head) [(arg, elab_qual None)] | T_ElimExists _ u t p _ d_t d_exists -> let ru = u in let rt = elab_term t in let rp = elab_term p in mk_elim_exists ru rt (mk_abs rt R.Q_Explicit rp) | T_IntroExists _ u b p e _ _ _ -> let ru = u in let rt = elab_term b.binder_ty in let rp = elab_term p in let re = elab_term e in mk_intro_exists ru rt (mk_abs rt R.Q_Explicit rp) re | T_While _ inv _ _ _ cond_typing body_typing -> let inv = elab_term inv in let cond = elab_st_typing cond_typing in let body = elab_st_typing body_typing in mk_while (mk_abs bool_tm R.Q_Explicit inv) cond body | T_Par _ eL cL eR cR _ _ _ eL_typing eR_typing -> let ru = comp_u cL in let raL = elab_term (comp_res cL) in let raR = elab_term (comp_res cR) in let rpreL = elab_term (comp_pre cL) in let rpostL = elab_term (comp_post cL) in let rpreR = elab_term (comp_pre cR) in let rpostR = elab_term (comp_post cR) in let reL = elab_st_typing eL_typing in let reR = elab_st_typing eR_typing in mk_par ru raL raR rpreL (mk_abs raL R.Q_Explicit rpostL) rpreR (mk_abs raR R.Q_Explicit rpostR) reL reR | T_Rewrite _ p q _ _ -> let rp = elab_term p in let rq = elab_term q in mk_rewrite rp rq | T_WithLocal _ _ init _ init_t c x _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_ref ra) R.Q_Explicit rbody in mk_withlocal rret_u ra rinit rpre rret_t rpost rbody | T_WithLocalArray _ _ init len _ init_t c x _ _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rlen = elab_term len in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_array ra) R.Q_Explicit rbody in mk_withlocalarray rret_u ra rinit rlen rpre rret_t rpost rbody | T_Admit _ {u;res;pre;post} c _ -> let ru = u in let rres = elab_term res in let rpre = elab_term pre in let rpost = elab_term post in let rpost = mk_abs rres R.Q_Explicit rpost in (match c with | STT -> mk_stt_admit ru rres rpre rpost | STT_Atomic -> mk_stt_atomic_admit ru rres rpre rpost | STT_Ghost -> mk_stt_ghost_admit ru rres rpre rpost) | T_Unreachable _ _ _ _ _ -> `("IOU: elab_st_typing of T_Unreachable") | T_WithInv _ _ _ _ _ _ _ _ _ -> `("IOU: elab_st_typing of T_WithInv") and elab_br (#g:env) (#c:comp_st) (#sc_u:universe) (#sc_ty:typ) (#sc:term) (#p:pattern) (#e:st_term) (d : br_typing g sc_u sc_ty sc p e c) : Tot R.branch (decreases d) = let TBR _ _ _ _ _ _ _ _ bs _ _ _ ed = d in let e = elab_st_typing ed in (elab_pat p, e) and elab_branches (#g:env) (#c:comp_st) (#sc_u:universe) (#sc_ty:typ) (#sc:term) (#brs:list branch) (d : brs_typing g sc_u sc_ty sc brs c) : Tot (list R.branch) (decreases d) = match d with | TBRS_0 _ -> [] | TBRS_1 _ p e bd _ d' -> elab_br bd :: elab_branches d'
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 34, "end_line": 356, "start_col": 0, "start_line": 163 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term) : Tot R.term = match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e let intro_pure_tm (p:term) = let open Pulse.Reflection.Util in wtag (Some STT_Ghost) (Tm_STApp { head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p; arg_qual = None; arg = tm_fstar (`()) Range.range_0 }) let simple_arr (t1 t2 : R.term) : R.term = let b = R.pack_binder { sort = t1; ppname = Sealed.seal "x"; qual = R.Q_Explicit; attrs = [] } in R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2))) let elab_st_sub (#g:env) (#c1 #c2 : comp) (d_sub : st_sub g c1 c2) : Tot (t:R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2))) = RU.magic_s "elab_st_sub"
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
d: Pulse.Typing.br_typing g sc_u sc_ty sc p e c -> Prims.Tot FStar.Stubs.Reflection.V2.Data.branch
Prims.Tot
[ "total", "" ]
[ "elab_st_typing", "elab_br", "elab_branches" ]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.comp_st", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.typ", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.pattern", "Pulse.Syntax.Base.st_term", "Pulse.Typing.br_typing", "Prims.list", "FStar.Stubs.Reflection.V2.Data.binding", "FStar.Reflection.Typing.bindings_ok_for_pat", "Pulse.Typing.Env.fstar_env", "Pulse.Elaborate.Pure.elab_pat", "Prims.squash", "Pulse.Typing.all_fresh", "FStar.List.Tot.Base.map", "Pulse.Typing.Env.binding", "Pulse.Typing.readback_binding", "Prims.b2t", "FStar.Pervasives.Native.uu___is_Some", "FStar.Pervasives.Native.tuple2", "FStar.Stubs.Reflection.Types.term", "FStar.Reflection.Typing.elaborate_pat", "Prims.l_not", "FStar.Stubs.Reflection.V2.Data.uu___is_Tv_Unknown", "FStar.Stubs.Reflection.V2.Builtins.inspect_ln", "FStar.Pervasives.Native.fst", "FStar.Pervasives.Native.__proj__Some__item__v", "Pulse.Syntax.Base.var", "Pulse.Typing.freshv", "Pulse.Typing.push_bindings", "Pulse.Typing.st_typing", "Pulse.Typing.Env.push_binding", "Pulse.Syntax.Base.Mkppname", "FStar.Sealed.seal", "Prims.string", "FStar.Range.range_0", "Pulse.Typing.mk_sq_eq2", "Pulse.Syntax.Base.tm_fstar", "FStar.Pervasives.Native.Mktuple2", "FStar.Stubs.Reflection.V2.Data.pattern", "Pulse.Elaborate.Core.elab_st_typing", "FStar.Stubs.Reflection.V2.Data.branch" ]
[ "mutual recursion" ]
false
false
false
false
false
let rec elab_br (#g: env) (#c: comp_st) (#sc_u: universe) (#sc_ty: typ) (#sc: term) (#p: pattern) (#e: st_term) (d: br_typing g sc_u sc_ty sc p e c) : Tot R.branch (decreases d) =
let TBR _ _ _ _ _ _ _ _ bs _ _ _ ed = d in let e = elab_st_typing ed in (elab_pat p, e)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.lift_exn_tac
val lift_exn_tac (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
val lift_exn_tac (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 61, "end_line": 269, "start_col": 0, "start_line": 266 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect:
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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 -> FStar.Tactics.PatternMatching.match_res b) -> aa: a -> FStar.Tactics.Effect.Tac b
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.V1.Derived.fail", "Prims.string", "FStar.Tactics.PatternMatching.string_of_match_exception" ]
[]
false
true
false
false
false
let lift_exn_tac #a #b (f: (a -> match_res b)) (aa: a) : Tac b =
match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.match_abspat
val match_abspat (#b #a: _) (abspat: a) (k: (abspat_continuation -> Tac (matching_solution -> Tac b))) : Tac b
val match_abspat (#b #a: _) (abspat: a) (k: (abspat_continuation -> Tac (matching_solution -> Tac b))) : Tac b
let match_abspat #b #a (abspat: a) (k: abspat_continuation -> Tac (matching_solution -> Tac b)) : Tac b = let goal = cur_goal () in let hypotheses = vars_of_env (cur_env ()) in let problem, continuation = interp_abspat abspat in solve_mp problem hypotheses goal (k continuation)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 51, "end_line": 776, "start_col": 0, "start_line": 770 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit (** Retrieve the function used to locate a value for a given abspat binder. **) let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit (** Construct a term fetching the value of an abspat argument from a quoted matching solution ``solution_term``. **) let abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec) : Tac term = let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit); (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in mk_app loc_fn locate_args (** Specialize a continuation of type ``abspat_continuation``. This constructs a fully applied version of `continuation`, but it requires a quoted solution to be passed in. **) let rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv) : Tac term = match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term::rest -> let n = List.Tot.length hoisted_args in //let bv = fresh_bv_named ("x" ^ (string_of_int n)) in let nb : binder = { ppname = seal ("x" ^ string_of_int n); sort = pack Tv_Unknown; uniq = fresh (); qual = Q_Explicit; attrs = [] ; } in pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args))) let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term:term) : Tac term = let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in let argspecs, body = continuation in hoist_and_apply body (map mk_arg_term argspecs) [] (** Specialize a continuation of type ``abspat_continuation``. This yields a quoted function taking a matching solution and running its body with appropriate bindings. **) let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term = let solution_binder = fresh_binder (`matching_solution) in let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in let applied = specialize_abspat_continuation' continuation solution_term in let thunked = pack (Tv_Abs solution_binder applied) in debug ("Specialized into " ^ (term_to_string thunked)); let normalized = beta_reduce thunked in debug ("… which reduces to " ^ (term_to_string normalized)); thunked (** Interpret a continuation of type ``abspat_continuation``. This yields a function taking a matching solution and running the body of the continuation with appropriate bindings. **) let interp_abspat_continuation (a:Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a) = let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied /// Putting it all together /// ======================= /// /// We now have all we need to use pattern-matching, short of a few convenience functions: (** Construct a matching problem from an abspat. **) let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) = matching_problem_of_abs (quote abspat) (** Construct an solve a matching problem. This higher-order function isn't very usable on its own — it's mostly a
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
abspat: a -> k: (_: FStar.Tactics.PatternMatching.abspat_continuation -> FStar.Tactics.Effect.Tac (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac b)) -> FStar.Tactics.Effect.Tac b
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.matching_problem", "FStar.Tactics.PatternMatching.solve_mp", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.interp_abspat", "Prims.list", "FStar.Stubs.Reflection.V2.Data.binding", "FStar.Stubs.Reflection.V2.Builtins.vars_of_env", "FStar.Stubs.Reflection.Types.env", "FStar.Tactics.V2.Derived.cur_env", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.V2.Derived.cur_goal" ]
[]
false
true
false
false
false
let match_abspat #b #a (abspat: a) (k: (abspat_continuation -> Tac (matching_solution -> Tac b))) : Tac b =
let goal = cur_goal () in let hypotheses = vars_of_env (cur_env ()) in let problem, continuation = interp_abspat abspat in solve_mp problem hypotheses goal (k continuation)
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.mustfail
val mustfail (#a: _) (t: (unit -> Tac a)) (message: string) : Tac unit
val mustfail (#a: _) (t: (unit -> Tac a)) (message: string) : Tac unit
let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> ()
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 16, "end_line": 132, "start_col": 0, "start_line": 129 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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: (_: Prims.unit -> FStar.Tactics.Effect.Tac a) -> message: Prims.string -> FStar.Tactics.Effect.Tac Prims.unit
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "Prims.string", "FStar.Tactics.V2.Derived.fail", "FStar.Pervasives.Native.option", "FStar.Tactics.V2.Derived.trytac" ]
[]
false
true
false
false
false
let mustfail #a (t: (unit -> Tac a)) (message: string) : Tac unit =
match trytac t with | Some _ -> fail message | None -> ()
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.string_of_match_exception
val string_of_match_exception : _: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.Effect.Tac Prims.string
let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)"
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 74, "end_line": 238, "start_col": 0, "start_line": 222 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
_: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.Effect.Tac Prims.string
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.PatternMatching.qn", "Prims.op_Hat", "Prims.string", "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.desc_of_pattern", "FStar.Stubs.Tactics.V2.Builtins.term_to_string", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.term_head", "FStar.Stubs.Reflection.Types.typ" ]
[]
false
true
false
false
false
let string_of_match_exception =
function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp \226\128\166``, or ``goal \226\128\166``)"
false
MerkleTree.Spec.fst
MerkleTree.Spec.mt_verify
val mt_verify: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> p:(path #hsz n) -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> padded_hash #hsz -> GTot prop
val mt_verify: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> p:(path #hsz n) -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> padded_hash #hsz -> GTot prop
let mt_verify #hsz #f #n p idx h rt = rt == mt_verify_ #_ #f p idx h
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "7d7bdc20f2033171e279c176b26e84f9069d23c6", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
{ "end_col": 32, "end_line": 274, "start_col": 0, "start_line": 273 }
module MerkleTree.Spec open FStar.Classical open FStar.Mul open FStar.Seq module S = FStar.Seq #set-options "--max_fuel 0 --max_ifuel 0 --z3rlimit 10" // For SHA2_256, this is is a sequence of 32 bytes // These are secret bytes, hence not an eqtype type hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz } type hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz) val sha256_compress: hash_fun_t #32 let sha256_compress src1 src2 = let sz = Spec.Hash.Definitions.SHA2_256 in let hash_alg = Spec.Hash.Definitions.SHA2_256 in let acc = Spec.Agile.Hash.init hash_alg in let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in Spec.Agile.Hash.finish hash_alg acc () /// For simplicity, we will specify the root for a sequence of [i] /// tags where [i <= 2^n] as the root of a full binary tree with [2^n] /// leaves obtained by padding the sequence with dummies. This /// requires extending the definitions of hashes and hash functions. Our /// extended definition of hash justifies skipping any concrete /// computation on dummies. noeq type padded_hash #hsz = | HRaw: hr:hash #hsz -> padded_hash #hsz | HPad // right padding to make the size of a Merkle tree a power of 2 val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz) let padded_hash_fun #hsz f lh rh = allow_inversion (padded_hash #hsz); match lh, rh with | HPad , _ -> HPad | _ , HPad -> lh | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr) noextract val hashes (#hsz:pos): Type0 let hashes #hsz = S.seq (padded_hash #hsz) type merkle_tree (#hsz:pos) n = hs:hashes #hsz {S.length hs = pow2 n} val mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz) let mt_get #_ #_ mt idx = S.index mt idx unfold let op_String_Access (#hsz:pos) = S.index #(padded_hash #hsz) #push-options "--max_fuel 1" val mt_left: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1) let mt_left #_ #n mt = S.slice mt 0 (pow2 (n-1)) val mt_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1) let mt_right #_ #n mt = S.slice mt (pow2 (n-1)) (pow2 n) val mt_left_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> Lemma (S.equal mt (mt_left mt @| mt_right mt)) let mt_left_right #_ #_ mt = () val hs_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes #hsz {S.length hs = 2 * n} -> GTot (nhs:hashes #hsz {S.length nhs = n}) let rec hs_next_lv #hsz #f #n hs = if n = 0 then S.empty else S.cons (padded_hash_fun #hsz f hs.[0] hs.[1]) (hs_next_lv #hsz #f #(n-1) (S.slice hs 2 (S.length hs))) val hs_next_lv_index: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes{S.length hs = 2 * n} -> i:nat{i < n} -> Lemma ((hs_next_lv #hsz #f #n hs).[i] == padded_hash_fun #hsz f hs.[2 * i] hs.[2 * i + 1]) let rec hs_next_lv_index #hsz #f #n hs i = if n = 0 || i = 0 then () else hs_next_lv_index #hsz #f #(n - 1) (S.slice hs 2 (S.length hs)) (i - 1) val hs_next_lv_slice: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes{S.length hs = 2 * n} -> i:nat -> j:nat{i <= j && j <= n} -> Lemma (requires True) (ensures S.equal (hs_next_lv #hsz #f #(j - i) (S.slice hs (2 * i) (2 * j))) (S.slice (hs_next_lv #hsz #f #n hs) i j)) (decreases (j - i)) let rec hs_next_lv_slice #hsz #f #n hs i j = if i = j then () else begin let x = S.slice hs (2 * i) (2 * j) in assert (S.equal (hs_next_lv #hsz #f #(j - i) x) (S.cons (padded_hash_fun #hsz f x.[0] x.[1]) (hs_next_lv #hsz #f #(j - i - 1) (S.slice x 2 (S.length x))))); hs_next_lv_slice #hsz #f #n hs (i + 1) j; hs_next_lv_index #hsz #f #n hs i end val mt_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> GTot (merkle_tree #hsz (n-1)) let mt_next_lv #_ #f #n mt = hs_next_lv #_ #f #(pow2 (n-1)) mt val mt_next_lv_mt_left: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n -> Lemma (S.equal (mt_next_lv #_ #f #_ (mt_left mt)) (mt_left (mt_next_lv #_ #f #_ mt))) let mt_next_lv_mt_left #hsz #f #n mt = hs_next_lv_slice #_ #f #(pow2 (n-1)) mt 0 (pow2 (n-2)) val mt_next_lv_mt_right: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n -> Lemma (S.equal (mt_next_lv #_ #f #_ (mt_right mt)) (mt_right (mt_next_lv #_ #f #_ mt))) let mt_next_lv_mt_right #hsz #f #n mt = hs_next_lv_slice #hsz #f #(pow2 (n-1)) mt (pow2 (n-2)) (pow2 (n-1)) val hs_next_lv_equiv: #hsz:pos -> #f:hash_fun_t #hsz -> j:nat -> n:pos{j <= 2 * n} -> hs1:hashes{S.length hs1 = 2 * n} -> hs2:hashes{S.length hs2 = 2 * n} -> Lemma (requires S.equal (S.slice hs1 0 j) (S.slice hs2 0 j)) (ensures S.equal (S.slice (hs_next_lv #hsz #f #n hs1) 0 (j / 2)) (S.slice (hs_next_lv #hsz #f #n hs2) 0 (j / 2))) let hs_next_lv_equiv #hsz #f j n hs1 hs2 = forall_intro (hs_next_lv_index #_ #f #n hs1); forall_intro (hs_next_lv_index #_ #f #n hs2); let hs1' = hs_next_lv #_ #f #n hs1 in let hs2' = hs_next_lv #_ #f #n hs2 in assert (forall (i:nat{i < j / 2}). hs1'.[i] == padded_hash_fun #hsz f hs1.[2 * i] hs1.[2 * i + 1]); assert (forall (i:nat{i < j / 2}). hs2'.[i] == padded_hash_fun #hsz f hs2.[2 * i] hs2.[2 * i + 1]); assert (forall (i:nat{i < j}). (S.slice hs1 0 j).[i] == (S.slice hs2 0 j).[i]); assert (forall (i:nat{i < j}). hs1.[i] == hs2.[i]); assert (forall (i:nat{i < j / 2}). hs1.[2 * i] == hs2.[2 * i]); assert (forall (i:nat{i < j / 2}). hs1.[2 * i + 1] == hs2.[2 * i + 1]); assert (forall (i:nat{i < j / 2}). hs1'.[i] == hs2'.[i]) val mt_next_lv_equiv: #hsz:pos -> #f:hash_fun_t #hsz -> j:nat -> n:pos{j <= pow2 n} -> mt1:merkle_tree #hsz n -> mt2:merkle_tree #hsz n -> Lemma (requires S.equal (S.slice mt1 0 j) (S.slice mt2 0 j)) (ensures S.equal (S.slice (mt_next_lv #_ #f #_ mt1) 0 (j / 2)) (S.slice (mt_next_lv #_ #f #_ mt2) 0 (j / 2))) let mt_next_lv_equiv #hsz #f j n mt1 mt2 = hs_next_lv_equiv #_ #f j (pow2 (n-1)) mt1 mt2 val hs_next_rel: #hsz:pos -> #f:hash_fun_t #hsz -> n:nat -> hs:hashes #hsz {S.length hs = 2 * n} -> nhs:hashes #hsz {S.length nhs = n} -> GTot Type0 let hs_next_rel #hsz #f n hs nhs = forall (i:nat{i < n}). S.index nhs i == padded_hash_fun #hsz f (S.index hs (2 * i)) (S.index hs (2 * i + 1)) val mt_next_rel: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree #hsz (n - 1) -> GTot Type0 let mt_next_rel #hsz #f n mt nmt = hs_next_rel #hsz #f (pow2 (n-1)) mt nmt val hs_next_rel_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> n:nat -> hs:hashes{S.length hs = 2 * n} -> nhs:hashes{S.length nhs = n} -> Lemma (requires hs_next_rel #_ #f n hs nhs) (ensures S.equal nhs (hs_next_lv #_ #f #n hs)) let rec hs_next_rel_next_lv #hsz #f n hs nhs = if n = 0 then () else hs_next_rel_next_lv #_ #f (n - 1) (S.slice hs 2 (S.length hs)) (S.slice nhs 1 (S.length nhs)) val mt_next_rel_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree (n - 1) -> Lemma (requires mt_next_rel #_ #f n mt nmt) (ensures S.equal nmt (mt_next_lv #_ #f mt)) let mt_next_rel_next_lv #hsz #f n mt nmt = hs_next_rel_next_lv #_ #f (pow2 (n-1)) mt nmt val mt_next_rel_upd_even: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree (n - 1) -> i:nat{i < pow2 (n-1)} -> v:padded_hash -> Lemma (requires mt_next_rel #_ #f n mt nmt) (ensures mt_next_rel #_ #f n (S.upd mt (2 * i) v) (S.upd nmt i (padded_hash_fun #hsz f v (S.index mt (2 * i + 1))))) let mt_next_rel_upd_even #hsz #f n mt nmt i v = () #push-options "--z3rlimit 10 --initial_fuel 1 --max_fuel 1 --initial_ifuel 1 --max_ifuel 1" val mt_next_rel_upd_even_pad: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree #hsz (n - 1) -> i:nat{i < pow2 (n-1)} -> v:padded_hash #hsz -> Lemma (requires (mt_next_rel #_ #f n mt nmt) /\ (S.index mt (2 * i + 1) == HPad)) (ensures (mt_next_rel #_ #f n (S.upd mt (2 * i) v) (S.upd nmt i v))) let mt_next_rel_upd_even_pad #hsz #f n mt nmt i v = () #pop-options val mt_next_rel_upd_odd: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree (n - 1) -> i:nat{i < pow2 (n-1)} -> v:padded_hash -> Lemma (requires mt_next_rel #_ #f n mt nmt) (ensures mt_next_rel #_ #f n (S.upd mt (2 * i + 1) v) (S.upd nmt i (padded_hash_fun #_ f (S.index mt (2 * i)) v))) let mt_next_rel_upd_odd #hsz #f n mt nmt i v = () // fournet: just [root]? val mt_get_root: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> GTot (padded_hash #hsz) let rec mt_get_root #hsz #f #n mt = if n = 0 then mt.[0] else mt_get_root #_ #f (mt_next_lv #_ #f mt) #push-options "--initial_fuel 2 --max_fuel 2" val mt_get_root_step: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> Lemma (mt_get_root #_ #f mt == padded_hash_fun #_ f (mt_get_root #_ #f (mt_left mt)) (mt_get_root #_ #f (mt_right mt))) let rec mt_get_root_step #hsz #f #n mt = if n = 1 then () else begin mt_get_root_step #_ #f (mt_next_lv #_ #f mt); mt_next_lv_mt_left #_ #f mt; mt_next_lv_mt_right #_ #f mt end #pop-options type path #hsz n = S.lseq (padded_hash #hsz) n /// We first specify full paths, including padding. val mt_get_path: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> i:nat{i < pow2 n} -> GTot (path #hsz n) let rec mt_get_path #hsz #f #n t i = if n = 0 then S.empty else S.cons (if i % 2 = 0 then t.[i + 1] else t.[i - 1]) (mt_get_path #_ #f (mt_next_lv #_ #f t) (i / 2)) val mt_verify_: #hsz:pos -> #f:hash_fun_t #hsz ->#n:nat -> p:path #hsz n -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> GTot (padded_hash #hsz) let rec mt_verify_ #hsz #f #n p idx h = if n = 0 then h else mt_verify_ #_ #f #(n-1) (S.tail p) (idx / 2) (if idx % 2 = 0 then padded_hash_fun #_ f h (S.head p) else padded_hash_fun #_ f (S.head p) h) val mt_verify: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "Spec.Agile.Hash.fsti.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "MerkleTree.Spec.fst" }
[ { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Seq", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "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": 1, "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": 10, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
p: MerkleTree.Spec.path n -> idx: Prims.nat{idx < Prims.pow2 n} -> h: MerkleTree.Spec.padded_hash -> rt: MerkleTree.Spec.padded_hash -> Prims.GTot Prims.prop
Prims.GTot
[ "sometrivial" ]
[]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "MerkleTree.Spec.path", "Prims.b2t", "Prims.op_LessThan", "Prims.pow2", "MerkleTree.Spec.padded_hash", "Prims.eq2", "MerkleTree.Spec.mt_verify_", "Prims.prop" ]
[]
false
false
false
false
true
let mt_verify #hsz #f #n p idx h rt =
rt == mt_verify_ #_ #f p idx h
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.fetch_eq_side
val fetch_eq_side: Prims.unit -> Tac (term * term)
val fetch_eq_side: Prims.unit -> Tac (term * term)
let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level"
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 39, "end_line": 88, "start_col": 0, "start_line": 62 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation:
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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 (FStar.Tactics.NamedView.term * FStar.Tactics.NamedView.term)
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.unit", "FStar.Tactics.NamedView.term", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Stubs.Reflection.Types.fv", "FStar.Stubs.Reflection.V2.Data.universes", "Prims.op_Equality", "Prims.string", "FStar.Reflection.V2.Derived.fv_to_string", "FStar.Reflection.V2.Derived.flatten_name", "FStar.Reflection.Const.squash_qn", "FStar.Reflection.Const.eq2_qn", "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.tuple2", "Prims.bool", "FStar.Tactics.V2.Derived.fail", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.inspect", "FStar.Stubs.Reflection.Types.typ", "FStar.Tactics.V2.Derived.cur_goal" ]
[]
false
true
false
false
false
let fetch_eq_side () : Tac (term * term) =
let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level"
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.string_of_matching_problem
val string_of_matching_problem : mp: FStar.Tactics.PatternMatching.matching_problem -> Prims.string
let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }"
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 26, "end_line": 372, "start_col": 0, "start_line": 360 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
mp: FStar.Tactics.PatternMatching.matching_problem -> Prims.string
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.PatternMatching.matching_problem", "Prims.op_Hat", "Prims.string", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_goal", "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.string_of_pattern", "FStar.String.concat", "FStar.List.Tot.Base.map", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_hyps", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_vars" ]
[]
false
false
false
true
false
let string_of_matching_problem mp =
let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }"
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.lift_exn_tactic
val lift_exn_tactic (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
val lift_exn_tactic (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex)
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 61, "end_line": 274, "start_col": 0, "start_line": 271 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex)
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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 -> FStar.Tactics.PatternMatching.match_res b) -> aa: a -> FStar.Tactics.Effect.Tac b
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.V1.Derived.fail", "Prims.string", "FStar.Tactics.PatternMatching.string_of_match_exception" ]
[]
false
true
false
false
false
let lift_exn_tactic #a #b (f: (a -> match_res b)) (aa: a) : Tac b =
match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex)
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_st_typing
val elab_st_typing (#g: env) (#t: st_term) (#c: comp) (d: st_typing g t c) : Tot R.term (decreases d)
val elab_st_typing (#g: env) (#t: st_term) (#c: comp) (d: st_typing g t c) : Tot R.term (decreases d)
let rec elab_st_typing (#g:env) (#t:st_term) (#c:comp) (d:st_typing g t c) : Tot R.term (decreases d) = match d with // | T_Tot _ t _ _ -> elab_term t | T_Abs _ x qual b _u body _c ty_typing body_typing -> let ty = elab_term b.binder_ty in let ppname = b.binder_ppname.name in let body = elab_st_typing body_typing in mk_abs_with_name ppname ty (elab_qual qual) (RT.close_term body x) //this closure should be provably redundant by strengthening the conditions on x | T_STApp _ head _ qual _ arg _ _ | T_STGhostApp _ head _ qual _ arg _ _ _ _ -> let head = elab_term head in let arg = elab_term arg in R.mk_app head [(arg, elab_qual qual)] | T_Return _ c use_eq u ty t post _ _ _ _ -> let ru = u in let rty = elab_term ty in let rt = elab_term t in let rp = elab_term post in let rp = mk_abs rty R.Q_Explicit rp in (match c, use_eq with | STT, true -> mk_stt_return ru rty rt rp | STT, false -> mk_stt_return_noeq ru rty rt rp | STT_Atomic, true -> mk_stt_atomic_return ru rty rt rp | STT_Atomic, false -> mk_stt_atomic_return_noeq ru rty rt rp | STT_Ghost, true -> mk_stt_ghost_return ru rty rt rp | STT_Ghost, false -> mk_stt_ghost_return_noeq ru rty rt rp) | T_Bind _ e1 e2 c1 c2 b x c e1_typing t_typing e2_typing bc -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in elab_bind bc e1 (mk_abs_with_name b.binder_ppname.name ty1 R.Q_Explicit (RT.close_term e2 x)) | T_BindFn _ _ _ c1 c2 b x e1_typing _u t_typing e2_typing c2_typing -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in RT.mk_let RT.pp_name_default e1 ty1 (RT.close_term e2 x) | T_Frame _ _ c frame _frame_typing e_typing -> let e = elab_st_typing e_typing in elab_frame c frame e | T_Equiv _ _ c1 c2 e_typing (ST_TotEquiv _ _ _ _ _ _) -> let e = elab_st_typing e_typing in e | T_Equiv _ _ c1 c2 e_typing _ -> let e = elab_st_typing e_typing in elab_sub c1 c2 e | T_Sub _ _ c1 c2 e_typing d_sub -> let e = elab_st_typing e_typing in let (| coercion, _ |) = elab_st_sub d_sub in R.mk_e_app coercion [e] | T_Lift _ _ c1 c2 e_typing lc -> let e = elab_st_typing e_typing in elab_lift lc e | T_If _ b _ _ _ _ _ e1_typing e2_typing _c_typing -> let rb = elab_term b in let re1 = elab_st_typing e1_typing in let re2 = elab_st_typing e2_typing in RT.mk_if rb re1 re2 | T_Match _ _ _ sc _ _ _ _ _ brty _ -> let sc = elab_term sc in let brs = elab_branches brty in R.pack_ln (R.Tv_Match sc None brs) | T_IntroPure _ p _ _ -> let head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p in let arg = (`()) in R.mk_app (elab_term head) [(arg, elab_qual None)] | T_ElimExists _ u t p _ d_t d_exists -> let ru = u in let rt = elab_term t in let rp = elab_term p in mk_elim_exists ru rt (mk_abs rt R.Q_Explicit rp) | T_IntroExists _ u b p e _ _ _ -> let ru = u in let rt = elab_term b.binder_ty in let rp = elab_term p in let re = elab_term e in mk_intro_exists ru rt (mk_abs rt R.Q_Explicit rp) re | T_While _ inv _ _ _ cond_typing body_typing -> let inv = elab_term inv in let cond = elab_st_typing cond_typing in let body = elab_st_typing body_typing in mk_while (mk_abs bool_tm R.Q_Explicit inv) cond body | T_Par _ eL cL eR cR _ _ _ eL_typing eR_typing -> let ru = comp_u cL in let raL = elab_term (comp_res cL) in let raR = elab_term (comp_res cR) in let rpreL = elab_term (comp_pre cL) in let rpostL = elab_term (comp_post cL) in let rpreR = elab_term (comp_pre cR) in let rpostR = elab_term (comp_post cR) in let reL = elab_st_typing eL_typing in let reR = elab_st_typing eR_typing in mk_par ru raL raR rpreL (mk_abs raL R.Q_Explicit rpostL) rpreR (mk_abs raR R.Q_Explicit rpostR) reL reR | T_Rewrite _ p q _ _ -> let rp = elab_term p in let rq = elab_term q in mk_rewrite rp rq | T_WithLocal _ _ init _ init_t c x _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_ref ra) R.Q_Explicit rbody in mk_withlocal rret_u ra rinit rpre rret_t rpost rbody | T_WithLocalArray _ _ init len _ init_t c x _ _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rlen = elab_term len in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_array ra) R.Q_Explicit rbody in mk_withlocalarray rret_u ra rinit rlen rpre rret_t rpost rbody | T_Admit _ {u;res;pre;post} c _ -> let ru = u in let rres = elab_term res in let rpre = elab_term pre in let rpost = elab_term post in let rpost = mk_abs rres R.Q_Explicit rpost in (match c with | STT -> mk_stt_admit ru rres rpre rpost | STT_Atomic -> mk_stt_atomic_admit ru rres rpre rpost | STT_Ghost -> mk_stt_ghost_admit ru rres rpre rpost) | T_Unreachable _ _ _ _ _ -> `("IOU: elab_st_typing of T_Unreachable") | T_WithInv _ _ _ _ _ _ _ _ _ -> `("IOU: elab_st_typing of T_WithInv") and elab_br (#g:env) (#c:comp_st) (#sc_u:universe) (#sc_ty:typ) (#sc:term) (#p:pattern) (#e:st_term) (d : br_typing g sc_u sc_ty sc p e c) : Tot R.branch (decreases d) = let TBR _ _ _ _ _ _ _ _ bs _ _ _ ed = d in let e = elab_st_typing ed in (elab_pat p, e) and elab_branches (#g:env) (#c:comp_st) (#sc_u:universe) (#sc_ty:typ) (#sc:term) (#brs:list branch) (d : brs_typing g sc_u sc_ty sc brs c) : Tot (list R.branch) (decreases d) = match d with | TBRS_0 _ -> [] | TBRS_1 _ p e bd _ d' -> elab_br bd :: elab_branches d'
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 34, "end_line": 356, "start_col": 0, "start_line": 163 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term) : Tot R.term = match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e let intro_pure_tm (p:term) = let open Pulse.Reflection.Util in wtag (Some STT_Ghost) (Tm_STApp { head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p; arg_qual = None; arg = tm_fstar (`()) Range.range_0 }) let simple_arr (t1 t2 : R.term) : R.term = let b = R.pack_binder { sort = t1; ppname = Sealed.seal "x"; qual = R.Q_Explicit; attrs = [] } in R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2))) let elab_st_sub (#g:env) (#c1 #c2 : comp) (d_sub : st_sub g c1 c2) : Tot (t:R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2))) = RU.magic_s "elab_st_sub"
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
d: Pulse.Typing.st_typing g t c -> Prims.Tot FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total", "" ]
[ "elab_st_typing", "elab_br", "elab_branches" ]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.st_term", "Pulse.Syntax.Base.comp", "Pulse.Typing.st_typing", "Pulse.Syntax.Base.var", "Prims.b2t", "FStar.Pervasives.Native.uu___is_None", "Pulse.Syntax.Base.typ", "Pulse.Typing.Env.lookup", "FStar.Pervasives.Native.option", "Pulse.Syntax.Base.qualifier", "Pulse.Syntax.Base.binder", "Pulse.Syntax.Base.universe", "Prims.l_not", "FStar.Set.mem", "Pulse.Syntax.Naming.freevars_st", "Pulse.Typing.tot_typing", "Pulse.Syntax.Base.__proj__Mkbinder__item__binder_ty", "Pulse.Syntax.Pure.tm_type", "Pulse.Typing.Env.push_binding", "Pulse.Syntax.Base.ppname_default", "Pulse.Syntax.Naming.open_st_term_nv", "FStar.Pervasives.Native.Mktuple2", "Pulse.Syntax.Base.ppname", "Pulse.Syntax.Base.__proj__Mkbinder__item__binder_ppname", "Pulse.Reflection.Util.mk_abs_with_name", "Pulse.Elaborate.Pure.elab_qual", "FStar.Reflection.Typing.close_term", "FStar.Stubs.Reflection.Types.term", "Pulse.Elaborate.Core.elab_st_typing", "FStar.Reflection.Typing.pp_name_t", "Pulse.Syntax.Base.__proj__Mkppname__item__name", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.comp_st", "Pulse.Syntax.Pure.tm_arrow", "Pulse.Syntax.Base.as_binder", "FStar.Reflection.V2.Derived.mk_app", "Prims.Cons", "FStar.Stubs.Reflection.V2.Data.argv", "FStar.Stubs.Reflection.V2.Data.aqualv", "Prims.Nil", "Prims.l_and", "Pulse.Syntax.Naming.freevars_comp", "Pulse.Typing.ghost_typing", "Pulse.Typing.non_informative", "Pulse.Syntax.Naming.open_comp_with", "Pulse.Syntax.Pure.null_var", "Pulse.Syntax.Base.ctag", "Prims.bool", "Pulse.Syntax.Naming.freevars", "Pulse.Typing.universe_of", "Pulse.Typing.typing", "Pulse.Typing.eff_of_ctag", "Pulse.Syntax.Naming.open_term", "Pulse.Syntax.Base.tm_vprop", "Pulse.Reflection.Util.mk_stt_return", "Pulse.Reflection.Util.mk_stt_return_noeq", "Pulse.Reflection.Util.mk_stt_atomic_return", "Pulse.Reflection.Util.mk_stt_atomic_return_noeq", "Pulse.Reflection.Util.mk_stt_ghost_return", "Pulse.Reflection.Util.mk_stt_ghost_return_noeq", "Pulse.Reflection.Util.mk_abs", "FStar.Stubs.Reflection.V2.Data.Q_Explicit", "Prims.eq2", "Pulse.Syntax.Base.comp_res", "Pulse.Syntax.Base.comp_u", "Pulse.Typing.bind_comp", "Pulse.Elaborate.Core.elab_bind", "Pulse.Syntax.Base.uu___is_C_Tot", "FStar.Ghost.erased", "FStar.Ghost.reveal", "Pulse.Typing.comp_typing_u", "FStar.Reflection.Typing.mk_let", "FStar.Reflection.Typing.pp_name_default", "Pulse.Elaborate.Core.elab_frame", "FStar.Reflection.Typing.equiv", "Pulse.Typing.elab_env", "Pulse.Typing.st_equiv", "Pulse.Elaborate.Core.elab_sub", "Pulse.Typing.st_sub", "FStar.Reflection.Typing.tot_typing", "Pulse.Elaborate.Core.simple_arr", "Pulse.Elaborate.Pure.elab_comp", "FStar.Reflection.V2.Derived.mk_e_app", "Prims.dtuple2", "Pulse.Elaborate.Core.elab_st_sub", "Pulse.Typing.lift_comp", "Pulse.Elaborate.Core.elab_lift", "FStar.Set.union", "Pulse.Typing.tm_bool", "Pulse.Typing.mk_eq2", "Pulse.Syntax.Pure.u0", "Pulse.Typing.tm_true", "Pulse.Typing.tm_false", "Pulse.Typing.my_erased", "FStar.Reflection.Typing.mk_if", "Prims.list", "FStar.Pervasives.Native.tuple2", "Pulse.Syntax.Base.pattern", "Pulse.Typing.brs_typing", "Pulse.Typing.pats_complete", "FStar.List.Tot.Base.map", "FStar.Stubs.Reflection.V2.Data.pattern", "Pulse.Elaborate.Pure.elab_pat", "FStar.Stubs.Reflection.V2.Builtins.pack_ln", "FStar.Stubs.Reflection.V2.Data.Tv_Match", "FStar.Pervasives.Native.None", "FStar.Stubs.Reflection.Types.match_returns_ascription", "FStar.Stubs.Reflection.V2.Data.branch", "Pulse.Elaborate.Core.elab_branches", "Pulse.Typing.tm_prop", "Pulse.Typing.prop_validity", "Pulse.Syntax.Pure.tm_pureapp", "Pulse.Syntax.Pure.tm_fvar", "Pulse.Syntax.Base.as_fv", "Pulse.Reflection.Util.mk_pulse_lib_core_lid", "Pulse.Syntax.Base.tm_exists_sl", "Pulse.Reflection.Util.mk_elim_exists", "Pulse.Reflection.Util.mk_intro_exists", "Pulse.Typing.comp_while_cond", "Pulse.Typing.comp_while_body", "Pulse.Reflection.Util.mk_while", "Pulse.Reflection.Util.bool_tm", "Pulse.Syntax.Base.uu___is_C_ST", "Pulse.Reflection.Util.mk_par", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.comp_pre", "Pulse.Syntax.Base.vprop", "Pulse.Typing.vprop_equiv", "Pulse.Reflection.Util.mk_rewrite", "Pulse.Typing.mk_ref", "Pulse.Syntax.Base.v_as_nv", "Pulse.Typing.comp_withlocal_body", "Pulse.Reflection.Util.mk_withlocal", "Pulse.Reflection.Util.mk_ref", "Pulse.Typing.tm_szt", "Pulse.Typing.mk_array", "Pulse.Typing.comp_withlocal_array_body", "Pulse.Reflection.Util.mk_withlocalarray", "Pulse.Reflection.Util.mk_array", "Pulse.Typing.st_comp_typing", "Pulse.Syntax.Base.Mkst_comp", "Pulse.Reflection.Util.mk_stt_admit", "Pulse.Reflection.Util.mk_stt_atomic_admit", "Pulse.Reflection.Util.mk_stt_ghost_admit", "Pulse.Syntax.Base.st_comp", "Pulse.Syntax.Base.tm_fstar", "FStar.Range.range_0", "Pulse.Syntax.Base.tm_inv", "Pulse.Syntax.Base.uu___is_C_STAtomic", "Pulse.Typing.add_frame", "Pulse.Typing.inv_disjointness", "Pulse.Syntax.Base.comp_inames" ]
[ "mutual recursion" ]
false
false
false
false
false
let rec elab_st_typing (#g: env) (#t: st_term) (#c: comp) (d: st_typing g t c) : Tot R.term (decreases d) =
match d with | T_Abs _ x qual b _u body _c ty_typing body_typing -> let ty = elab_term b.binder_ty in let ppname = b.binder_ppname.name in let body = elab_st_typing body_typing in mk_abs_with_name ppname ty (elab_qual qual) (RT.close_term body x) | T_STApp _ head _ qual _ arg _ _ | T_STGhostApp _ head _ qual _ arg _ _ _ _ -> let head = elab_term head in let arg = elab_term arg in R.mk_app head [(arg, elab_qual qual)] | T_Return _ c use_eq u ty t post _ _ _ _ -> let ru = u in let rty = elab_term ty in let rt = elab_term t in let rp = elab_term post in let rp = mk_abs rty R.Q_Explicit rp in (match c, use_eq with | STT, true -> mk_stt_return ru rty rt rp | STT, false -> mk_stt_return_noeq ru rty rt rp | STT_Atomic, true -> mk_stt_atomic_return ru rty rt rp | STT_Atomic, false -> mk_stt_atomic_return_noeq ru rty rt rp | STT_Ghost, true -> mk_stt_ghost_return ru rty rt rp | STT_Ghost, false -> mk_stt_ghost_return_noeq ru rty rt rp) | T_Bind _ e1 e2 c1 c2 b x c e1_typing t_typing e2_typing bc -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in elab_bind bc e1 (mk_abs_with_name b.binder_ppname.name ty1 R.Q_Explicit (RT.close_term e2 x)) | T_BindFn _ _ _ c1 c2 b x e1_typing _u t_typing e2_typing c2_typing -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in RT.mk_let RT.pp_name_default e1 ty1 (RT.close_term e2 x) | T_Frame _ _ c frame _frame_typing e_typing -> let e = elab_st_typing e_typing in elab_frame c frame e | T_Equiv _ _ c1 c2 e_typing (ST_TotEquiv _ _ _ _ _ _) -> let e = elab_st_typing e_typing in e | T_Equiv _ _ c1 c2 e_typing _ -> let e = elab_st_typing e_typing in elab_sub c1 c2 e | T_Sub _ _ c1 c2 e_typing d_sub -> let e = elab_st_typing e_typing in let (| coercion , _ |) = elab_st_sub d_sub in R.mk_e_app coercion [e] | T_Lift _ _ c1 c2 e_typing lc -> let e = elab_st_typing e_typing in elab_lift lc e | T_If _ b _ _ _ _ _ e1_typing e2_typing _c_typing -> let rb = elab_term b in let re1 = elab_st_typing e1_typing in let re2 = elab_st_typing e2_typing in RT.mk_if rb re1 re2 | T_Match _ _ _ sc _ _ _ _ _ brty _ -> let sc = elab_term sc in let brs = elab_branches brty in R.pack_ln (R.Tv_Match sc None brs) | T_IntroPure _ p _ _ -> let head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p in let arg = (`()) in R.mk_app (elab_term head) [(arg, elab_qual None)] | T_ElimExists _ u t p _ d_t d_exists -> let ru = u in let rt = elab_term t in let rp = elab_term p in mk_elim_exists ru rt (mk_abs rt R.Q_Explicit rp) | T_IntroExists _ u b p e _ _ _ -> let ru = u in let rt = elab_term b.binder_ty in let rp = elab_term p in let re = elab_term e in mk_intro_exists ru rt (mk_abs rt R.Q_Explicit rp) re | T_While _ inv _ _ _ cond_typing body_typing -> let inv = elab_term inv in let cond = elab_st_typing cond_typing in let body = elab_st_typing body_typing in mk_while (mk_abs bool_tm R.Q_Explicit inv) cond body | T_Par _ eL cL eR cR _ _ _ eL_typing eR_typing -> let ru = comp_u cL in let raL = elab_term (comp_res cL) in let raR = elab_term (comp_res cR) in let rpreL = elab_term (comp_pre cL) in let rpostL = elab_term (comp_post cL) in let rpreR = elab_term (comp_pre cR) in let rpostR = elab_term (comp_post cR) in let reL = elab_st_typing eL_typing in let reR = elab_st_typing eR_typing in mk_par ru raL raR rpreL (mk_abs raL R.Q_Explicit rpostL) rpreR (mk_abs raR R.Q_Explicit rpostR) reL reR | T_Rewrite _ p q _ _ -> let rp = elab_term p in let rq = elab_term q in mk_rewrite rp rq | T_WithLocal _ _ init _ init_t c x _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_ref ra) R.Q_Explicit rbody in mk_withlocal rret_u ra rinit rpre rret_t rpost rbody | T_WithLocalArray _ _ init len _ init_t c x _ _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rlen = elab_term len in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_array ra) R.Q_Explicit rbody in mk_withlocalarray rret_u ra rinit rlen rpre rret_t rpost rbody | T_Admit _ { u = u ; res = res ; pre = pre ; post = post } c _ -> let ru = u in let rres = elab_term res in let rpre = elab_term pre in let rpost = elab_term post in let rpost = mk_abs rres R.Q_Explicit rpost in (match c with | STT -> mk_stt_admit ru rres rpre rpost | STT_Atomic -> mk_stt_atomic_admit ru rres rpre rpost | STT_Ghost -> mk_stt_ghost_admit ru rres rpre rpost) | T_Unreachable _ _ _ _ _ -> `("IOU: elab_st_typing of T_Unreachable") | T_WithInv _ _ _ _ _ _ _ _ _ -> `("IOU: elab_st_typing of T_WithInv")
false
Pulse.Elaborate.Core.fst
Pulse.Elaborate.Core.elab_branches
val elab_branches (#g: env) (#c: comp_st) (#sc_u: universe) (#sc_ty: typ) (#sc: term) (#brs: list branch) (d: brs_typing g sc_u sc_ty sc brs c) : Tot (list R.branch) (decreases d)
val elab_branches (#g: env) (#c: comp_st) (#sc_u: universe) (#sc_ty: typ) (#sc: term) (#brs: list branch) (d: brs_typing g sc_u sc_ty sc brs c) : Tot (list R.branch) (decreases d)
let rec elab_st_typing (#g:env) (#t:st_term) (#c:comp) (d:st_typing g t c) : Tot R.term (decreases d) = match d with // | T_Tot _ t _ _ -> elab_term t | T_Abs _ x qual b _u body _c ty_typing body_typing -> let ty = elab_term b.binder_ty in let ppname = b.binder_ppname.name in let body = elab_st_typing body_typing in mk_abs_with_name ppname ty (elab_qual qual) (RT.close_term body x) //this closure should be provably redundant by strengthening the conditions on x | T_STApp _ head _ qual _ arg _ _ | T_STGhostApp _ head _ qual _ arg _ _ _ _ -> let head = elab_term head in let arg = elab_term arg in R.mk_app head [(arg, elab_qual qual)] | T_Return _ c use_eq u ty t post _ _ _ _ -> let ru = u in let rty = elab_term ty in let rt = elab_term t in let rp = elab_term post in let rp = mk_abs rty R.Q_Explicit rp in (match c, use_eq with | STT, true -> mk_stt_return ru rty rt rp | STT, false -> mk_stt_return_noeq ru rty rt rp | STT_Atomic, true -> mk_stt_atomic_return ru rty rt rp | STT_Atomic, false -> mk_stt_atomic_return_noeq ru rty rt rp | STT_Ghost, true -> mk_stt_ghost_return ru rty rt rp | STT_Ghost, false -> mk_stt_ghost_return_noeq ru rty rt rp) | T_Bind _ e1 e2 c1 c2 b x c e1_typing t_typing e2_typing bc -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in elab_bind bc e1 (mk_abs_with_name b.binder_ppname.name ty1 R.Q_Explicit (RT.close_term e2 x)) | T_BindFn _ _ _ c1 c2 b x e1_typing _u t_typing e2_typing c2_typing -> let e1 = elab_st_typing e1_typing in let e2 = elab_st_typing e2_typing in let ty1 = elab_term (comp_res c1) in RT.mk_let RT.pp_name_default e1 ty1 (RT.close_term e2 x) | T_Frame _ _ c frame _frame_typing e_typing -> let e = elab_st_typing e_typing in elab_frame c frame e | T_Equiv _ _ c1 c2 e_typing (ST_TotEquiv _ _ _ _ _ _) -> let e = elab_st_typing e_typing in e | T_Equiv _ _ c1 c2 e_typing _ -> let e = elab_st_typing e_typing in elab_sub c1 c2 e | T_Sub _ _ c1 c2 e_typing d_sub -> let e = elab_st_typing e_typing in let (| coercion, _ |) = elab_st_sub d_sub in R.mk_e_app coercion [e] | T_Lift _ _ c1 c2 e_typing lc -> let e = elab_st_typing e_typing in elab_lift lc e | T_If _ b _ _ _ _ _ e1_typing e2_typing _c_typing -> let rb = elab_term b in let re1 = elab_st_typing e1_typing in let re2 = elab_st_typing e2_typing in RT.mk_if rb re1 re2 | T_Match _ _ _ sc _ _ _ _ _ brty _ -> let sc = elab_term sc in let brs = elab_branches brty in R.pack_ln (R.Tv_Match sc None brs) | T_IntroPure _ p _ _ -> let head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p in let arg = (`()) in R.mk_app (elab_term head) [(arg, elab_qual None)] | T_ElimExists _ u t p _ d_t d_exists -> let ru = u in let rt = elab_term t in let rp = elab_term p in mk_elim_exists ru rt (mk_abs rt R.Q_Explicit rp) | T_IntroExists _ u b p e _ _ _ -> let ru = u in let rt = elab_term b.binder_ty in let rp = elab_term p in let re = elab_term e in mk_intro_exists ru rt (mk_abs rt R.Q_Explicit rp) re | T_While _ inv _ _ _ cond_typing body_typing -> let inv = elab_term inv in let cond = elab_st_typing cond_typing in let body = elab_st_typing body_typing in mk_while (mk_abs bool_tm R.Q_Explicit inv) cond body | T_Par _ eL cL eR cR _ _ _ eL_typing eR_typing -> let ru = comp_u cL in let raL = elab_term (comp_res cL) in let raR = elab_term (comp_res cR) in let rpreL = elab_term (comp_pre cL) in let rpostL = elab_term (comp_post cL) in let rpreR = elab_term (comp_pre cR) in let rpostR = elab_term (comp_post cR) in let reL = elab_st_typing eL_typing in let reR = elab_st_typing eR_typing in mk_par ru raL raR rpreL (mk_abs raL R.Q_Explicit rpostL) rpreR (mk_abs raR R.Q_Explicit rpostR) reL reR | T_Rewrite _ p q _ _ -> let rp = elab_term p in let rq = elab_term q in mk_rewrite rp rq | T_WithLocal _ _ init _ init_t c x _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_ref ra) R.Q_Explicit rbody in mk_withlocal rret_u ra rinit rpre rret_t rpost rbody | T_WithLocalArray _ _ init len _ init_t c x _ _ _ _ body_typing -> let rret_u = comp_u c in let ra = elab_term init_t in let rinit = elab_term init in let rlen = elab_term len in let rret_t = elab_term (comp_res c) in let rpre = elab_term (comp_pre c) in let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in let rbody = elab_st_typing body_typing in let rbody = RT.close_term rbody x in let rbody = mk_abs (mk_array ra) R.Q_Explicit rbody in mk_withlocalarray rret_u ra rinit rlen rpre rret_t rpost rbody | T_Admit _ {u;res;pre;post} c _ -> let ru = u in let rres = elab_term res in let rpre = elab_term pre in let rpost = elab_term post in let rpost = mk_abs rres R.Q_Explicit rpost in (match c with | STT -> mk_stt_admit ru rres rpre rpost | STT_Atomic -> mk_stt_atomic_admit ru rres rpre rpost | STT_Ghost -> mk_stt_ghost_admit ru rres rpre rpost) | T_Unreachable _ _ _ _ _ -> `("IOU: elab_st_typing of T_Unreachable") | T_WithInv _ _ _ _ _ _ _ _ _ -> `("IOU: elab_st_typing of T_WithInv") and elab_br (#g:env) (#c:comp_st) (#sc_u:universe) (#sc_ty:typ) (#sc:term) (#p:pattern) (#e:st_term) (d : br_typing g sc_u sc_ty sc p e c) : Tot R.branch (decreases d) = let TBR _ _ _ _ _ _ _ _ bs _ _ _ ed = d in let e = elab_st_typing ed in (elab_pat p, e) and elab_branches (#g:env) (#c:comp_st) (#sc_u:universe) (#sc_ty:typ) (#sc:term) (#brs:list branch) (d : brs_typing g sc_u sc_ty sc brs c) : Tot (list R.branch) (decreases d) = match d with | TBRS_0 _ -> [] | TBRS_1 _ p e bd _ d' -> elab_br bd :: elab_branches d'
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "f984200f79bdc452374ae994a5ca837496476c41", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
{ "end_col": 34, "end_line": 356, "start_col": 0, "start_line": 163 }
(* Copyright 2023 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 Pulse.Elaborate.Core module RT = FStar.Reflection.Typing module R = FStar.Reflection.V2 module L = FStar.List.Tot module T = FStar.Tactics.V2 open FStar.List.Tot open Pulse.Syntax open Pulse.Elaborate.Pure open Pulse.Typing module RU = Pulse.RuntimeUtils open Pulse.Reflection.Util let elab_frame (c:comp_st) (frame:term) (e:R.term) = let u = comp_u c in let ty = elab_term (comp_res c) in let pre = elab_term (comp_pre c) in let post = elab_term (comp_post c) in if C_ST? c then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else if C_STAtomic? c then let opened = elab_term (comp_inames c) in mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e let elab_sub (c1 c2:comp_st) (e:R.term) = let ty = elab_term (comp_res c1) in let u = comp_u c1 in let pre1 = elab_term (comp_pre c1) in let pre2 = elab_term (comp_pre c2) in let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in if C_ST? c1 then mk_sub_stt u ty pre1 pre2 post1 post2 e else if C_STAtomic? c1 then let opened = elab_term (comp_inames c1) in mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e let elab_bind #g #x #c1 #c2 #c (bc:bind_comp g x c1 c2 c) (e1 e2:R.term) : R.term = let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match c1 with | C_ST _ -> mk_bind_stt (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STGhost _ -> mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 | C_STAtomic inames obs1 _ -> let C_STAtomic _ obs2 _ = c2 in mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2) (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1)) (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1))) (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2 let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term) : Tot R.term = match d with | Lift_STAtomic_ST _ _ -> let t = elab_term (comp_res c1) in mk_lift_atomic_stt (comp_u c1) (elab_term (comp_res c1)) t (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Observability _ c o2 -> let t = elab_term (comp_res c1) in mk_lift_observability (comp_u c1) (elab_observability (C_STAtomic?.obs c)) (elab_observability o2) (elab_term (comp_inames c1)) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_neutral (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a) | Lift_Neutral_Ghost _ c -> let t = elab_term (comp_res c1) in mk_lift_neutral_ghost (comp_u c1) t (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e let intro_pure_tm (p:term) = let open Pulse.Reflection.Util in wtag (Some STT_Ghost) (Tm_STApp { head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid "intro_pure"))) None p; arg_qual = None; arg = tm_fstar (`()) Range.range_0 }) let simple_arr (t1 t2 : R.term) : R.term = let b = R.pack_binder { sort = t1; ppname = Sealed.seal "x"; qual = R.Q_Explicit; attrs = [] } in R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2))) let elab_st_sub (#g:env) (#c1 #c2 : comp) (d_sub : st_sub g c1 c2) : Tot (t:R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2))) = RU.magic_s "elab_st_sub"
{ "checked_file": "/", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.RuntimeUtils.fsti.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Sealed.fsti.checked", "FStar.Reflection.V2.fst.checked", "FStar.Reflection.Typing.fsti.checked", "FStar.Range.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.fst.checked" ], "interface_file": false, "source_file": "Pulse.Elaborate.Core.fst" }
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "abbrev": true, "full_module": "Pulse.RuntimeUtils", "short_module": "RU" }, { "abbrev": false, "full_module": "Pulse.Typing", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate.Pure", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Syntax", "short_module": null }, { "abbrev": false, "full_module": "FStar.List.Tot", "short_module": null }, { "abbrev": true, "full_module": "FStar.Tactics.V2", "short_module": "T" }, { "abbrev": true, "full_module": "FStar.List.Tot", "short_module": "L" }, { "abbrev": true, "full_module": "FStar.Reflection.V2", "short_module": "R" }, { "abbrev": true, "full_module": "FStar.Reflection.Typing", "short_module": "RT" }, { "abbrev": false, "full_module": "Pulse.Elaborate", "short_module": null }, { "abbrev": false, "full_module": "Pulse.Elaborate", "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
d: Pulse.Typing.brs_typing g sc_u sc_ty sc brs c -> Prims.Tot (Prims.list FStar.Stubs.Reflection.V2.Data.branch)
Prims.Tot
[ "total", "" ]
[ "elab_st_typing", "elab_br", "elab_branches" ]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.comp_st", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.typ", "Pulse.Syntax.Base.term", "Prims.list", "Pulse.Syntax.Base.branch", "Pulse.Typing.brs_typing", "Prims.Nil", "FStar.Stubs.Reflection.V2.Data.branch", "Pulse.Syntax.Base.pattern", "Pulse.Syntax.Base.st_term", "Pulse.Typing.br_typing", "Prims.Cons", "Pulse.Elaborate.Core.elab_br", "Pulse.Elaborate.Core.elab_branches" ]
[ "mutual recursion" ]
false
false
false
false
false
let rec elab_branches (#g: env) (#c: comp_st) (#sc_u: universe) (#sc_ty: typ) (#sc: term) (#brs: list branch) (d: brs_typing g sc_u sc_ty sc brs c) : Tot (list R.branch) (decreases d) =
match d with | TBRS_0 _ -> [] | TBRS_1 _ p e bd _ d' -> elab_br bd :: elab_branches d'
false
MerkleTree.Spec.fst
MerkleTree.Spec.pad_hashes
val pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Type0
val pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Type0
let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad)
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "7d7bdc20f2033171e279c176b26e84f9069d23c6", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
{ "end_col": 42, "end_line": 368, "start_col": 0, "start_line": 367 }
module MerkleTree.Spec open FStar.Classical open FStar.Mul open FStar.Seq module S = FStar.Seq #set-options "--max_fuel 0 --max_ifuel 0 --z3rlimit 10" // For SHA2_256, this is is a sequence of 32 bytes // These are secret bytes, hence not an eqtype type hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz } type hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz) val sha256_compress: hash_fun_t #32 let sha256_compress src1 src2 = let sz = Spec.Hash.Definitions.SHA2_256 in let hash_alg = Spec.Hash.Definitions.SHA2_256 in let acc = Spec.Agile.Hash.init hash_alg in let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in Spec.Agile.Hash.finish hash_alg acc () /// For simplicity, we will specify the root for a sequence of [i] /// tags where [i <= 2^n] as the root of a full binary tree with [2^n] /// leaves obtained by padding the sequence with dummies. This /// requires extending the definitions of hashes and hash functions. Our /// extended definition of hash justifies skipping any concrete /// computation on dummies. noeq type padded_hash #hsz = | HRaw: hr:hash #hsz -> padded_hash #hsz | HPad // right padding to make the size of a Merkle tree a power of 2 val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz) let padded_hash_fun #hsz f lh rh = allow_inversion (padded_hash #hsz); match lh, rh with | HPad , _ -> HPad | _ , HPad -> lh | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr) noextract val hashes (#hsz:pos): Type0 let hashes #hsz = S.seq (padded_hash #hsz) type merkle_tree (#hsz:pos) n = hs:hashes #hsz {S.length hs = pow2 n} val mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz) let mt_get #_ #_ mt idx = S.index mt idx unfold let op_String_Access (#hsz:pos) = S.index #(padded_hash #hsz) #push-options "--max_fuel 1" val mt_left: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1) let mt_left #_ #n mt = S.slice mt 0 (pow2 (n-1)) val mt_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1) let mt_right #_ #n mt = S.slice mt (pow2 (n-1)) (pow2 n) val mt_left_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> Lemma (S.equal mt (mt_left mt @| mt_right mt)) let mt_left_right #_ #_ mt = () val hs_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes #hsz {S.length hs = 2 * n} -> GTot (nhs:hashes #hsz {S.length nhs = n}) let rec hs_next_lv #hsz #f #n hs = if n = 0 then S.empty else S.cons (padded_hash_fun #hsz f hs.[0] hs.[1]) (hs_next_lv #hsz #f #(n-1) (S.slice hs 2 (S.length hs))) val hs_next_lv_index: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes{S.length hs = 2 * n} -> i:nat{i < n} -> Lemma ((hs_next_lv #hsz #f #n hs).[i] == padded_hash_fun #hsz f hs.[2 * i] hs.[2 * i + 1]) let rec hs_next_lv_index #hsz #f #n hs i = if n = 0 || i = 0 then () else hs_next_lv_index #hsz #f #(n - 1) (S.slice hs 2 (S.length hs)) (i - 1) val hs_next_lv_slice: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes{S.length hs = 2 * n} -> i:nat -> j:nat{i <= j && j <= n} -> Lemma (requires True) (ensures S.equal (hs_next_lv #hsz #f #(j - i) (S.slice hs (2 * i) (2 * j))) (S.slice (hs_next_lv #hsz #f #n hs) i j)) (decreases (j - i)) let rec hs_next_lv_slice #hsz #f #n hs i j = if i = j then () else begin let x = S.slice hs (2 * i) (2 * j) in assert (S.equal (hs_next_lv #hsz #f #(j - i) x) (S.cons (padded_hash_fun #hsz f x.[0] x.[1]) (hs_next_lv #hsz #f #(j - i - 1) (S.slice x 2 (S.length x))))); hs_next_lv_slice #hsz #f #n hs (i + 1) j; hs_next_lv_index #hsz #f #n hs i end val mt_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> GTot (merkle_tree #hsz (n-1)) let mt_next_lv #_ #f #n mt = hs_next_lv #_ #f #(pow2 (n-1)) mt val mt_next_lv_mt_left: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n -> Lemma (S.equal (mt_next_lv #_ #f #_ (mt_left mt)) (mt_left (mt_next_lv #_ #f #_ mt))) let mt_next_lv_mt_left #hsz #f #n mt = hs_next_lv_slice #_ #f #(pow2 (n-1)) mt 0 (pow2 (n-2)) val mt_next_lv_mt_right: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n -> Lemma (S.equal (mt_next_lv #_ #f #_ (mt_right mt)) (mt_right (mt_next_lv #_ #f #_ mt))) let mt_next_lv_mt_right #hsz #f #n mt = hs_next_lv_slice #hsz #f #(pow2 (n-1)) mt (pow2 (n-2)) (pow2 (n-1)) val hs_next_lv_equiv: #hsz:pos -> #f:hash_fun_t #hsz -> j:nat -> n:pos{j <= 2 * n} -> hs1:hashes{S.length hs1 = 2 * n} -> hs2:hashes{S.length hs2 = 2 * n} -> Lemma (requires S.equal (S.slice hs1 0 j) (S.slice hs2 0 j)) (ensures S.equal (S.slice (hs_next_lv #hsz #f #n hs1) 0 (j / 2)) (S.slice (hs_next_lv #hsz #f #n hs2) 0 (j / 2))) let hs_next_lv_equiv #hsz #f j n hs1 hs2 = forall_intro (hs_next_lv_index #_ #f #n hs1); forall_intro (hs_next_lv_index #_ #f #n hs2); let hs1' = hs_next_lv #_ #f #n hs1 in let hs2' = hs_next_lv #_ #f #n hs2 in assert (forall (i:nat{i < j / 2}). hs1'.[i] == padded_hash_fun #hsz f hs1.[2 * i] hs1.[2 * i + 1]); assert (forall (i:nat{i < j / 2}). hs2'.[i] == padded_hash_fun #hsz f hs2.[2 * i] hs2.[2 * i + 1]); assert (forall (i:nat{i < j}). (S.slice hs1 0 j).[i] == (S.slice hs2 0 j).[i]); assert (forall (i:nat{i < j}). hs1.[i] == hs2.[i]); assert (forall (i:nat{i < j / 2}). hs1.[2 * i] == hs2.[2 * i]); assert (forall (i:nat{i < j / 2}). hs1.[2 * i + 1] == hs2.[2 * i + 1]); assert (forall (i:nat{i < j / 2}). hs1'.[i] == hs2'.[i]) val mt_next_lv_equiv: #hsz:pos -> #f:hash_fun_t #hsz -> j:nat -> n:pos{j <= pow2 n} -> mt1:merkle_tree #hsz n -> mt2:merkle_tree #hsz n -> Lemma (requires S.equal (S.slice mt1 0 j) (S.slice mt2 0 j)) (ensures S.equal (S.slice (mt_next_lv #_ #f #_ mt1) 0 (j / 2)) (S.slice (mt_next_lv #_ #f #_ mt2) 0 (j / 2))) let mt_next_lv_equiv #hsz #f j n mt1 mt2 = hs_next_lv_equiv #_ #f j (pow2 (n-1)) mt1 mt2 val hs_next_rel: #hsz:pos -> #f:hash_fun_t #hsz -> n:nat -> hs:hashes #hsz {S.length hs = 2 * n} -> nhs:hashes #hsz {S.length nhs = n} -> GTot Type0 let hs_next_rel #hsz #f n hs nhs = forall (i:nat{i < n}). S.index nhs i == padded_hash_fun #hsz f (S.index hs (2 * i)) (S.index hs (2 * i + 1)) val mt_next_rel: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree #hsz (n - 1) -> GTot Type0 let mt_next_rel #hsz #f n mt nmt = hs_next_rel #hsz #f (pow2 (n-1)) mt nmt val hs_next_rel_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> n:nat -> hs:hashes{S.length hs = 2 * n} -> nhs:hashes{S.length nhs = n} -> Lemma (requires hs_next_rel #_ #f n hs nhs) (ensures S.equal nhs (hs_next_lv #_ #f #n hs)) let rec hs_next_rel_next_lv #hsz #f n hs nhs = if n = 0 then () else hs_next_rel_next_lv #_ #f (n - 1) (S.slice hs 2 (S.length hs)) (S.slice nhs 1 (S.length nhs)) val mt_next_rel_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree (n - 1) -> Lemma (requires mt_next_rel #_ #f n mt nmt) (ensures S.equal nmt (mt_next_lv #_ #f mt)) let mt_next_rel_next_lv #hsz #f n mt nmt = hs_next_rel_next_lv #_ #f (pow2 (n-1)) mt nmt val mt_next_rel_upd_even: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree (n - 1) -> i:nat{i < pow2 (n-1)} -> v:padded_hash -> Lemma (requires mt_next_rel #_ #f n mt nmt) (ensures mt_next_rel #_ #f n (S.upd mt (2 * i) v) (S.upd nmt i (padded_hash_fun #hsz f v (S.index mt (2 * i + 1))))) let mt_next_rel_upd_even #hsz #f n mt nmt i v = () #push-options "--z3rlimit 10 --initial_fuel 1 --max_fuel 1 --initial_ifuel 1 --max_ifuel 1" val mt_next_rel_upd_even_pad: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree #hsz (n - 1) -> i:nat{i < pow2 (n-1)} -> v:padded_hash #hsz -> Lemma (requires (mt_next_rel #_ #f n mt nmt) /\ (S.index mt (2 * i + 1) == HPad)) (ensures (mt_next_rel #_ #f n (S.upd mt (2 * i) v) (S.upd nmt i v))) let mt_next_rel_upd_even_pad #hsz #f n mt nmt i v = () #pop-options val mt_next_rel_upd_odd: #hsz:pos -> #f:hash_fun_t #hsz -> n:pos -> mt:merkle_tree #hsz n -> nmt:merkle_tree (n - 1) -> i:nat{i < pow2 (n-1)} -> v:padded_hash -> Lemma (requires mt_next_rel #_ #f n mt nmt) (ensures mt_next_rel #_ #f n (S.upd mt (2 * i + 1) v) (S.upd nmt i (padded_hash_fun #_ f (S.index mt (2 * i)) v))) let mt_next_rel_upd_odd #hsz #f n mt nmt i v = () // fournet: just [root]? val mt_get_root: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> GTot (padded_hash #hsz) let rec mt_get_root #hsz #f #n mt = if n = 0 then mt.[0] else mt_get_root #_ #f (mt_next_lv #_ #f mt) #push-options "--initial_fuel 2 --max_fuel 2" val mt_get_root_step: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> Lemma (mt_get_root #_ #f mt == padded_hash_fun #_ f (mt_get_root #_ #f (mt_left mt)) (mt_get_root #_ #f (mt_right mt))) let rec mt_get_root_step #hsz #f #n mt = if n = 1 then () else begin mt_get_root_step #_ #f (mt_next_lv #_ #f mt); mt_next_lv_mt_left #_ #f mt; mt_next_lv_mt_right #_ #f mt end #pop-options type path #hsz n = S.lseq (padded_hash #hsz) n /// We first specify full paths, including padding. val mt_get_path: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> i:nat{i < pow2 n} -> GTot (path #hsz n) let rec mt_get_path #hsz #f #n t i = if n = 0 then S.empty else S.cons (if i % 2 = 0 then t.[i + 1] else t.[i - 1]) (mt_get_path #_ #f (mt_next_lv #_ #f t) (i / 2)) val mt_verify_: #hsz:pos -> #f:hash_fun_t #hsz ->#n:nat -> p:path #hsz n -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> GTot (padded_hash #hsz) let rec mt_verify_ #hsz #f #n p idx h = if n = 0 then h else mt_verify_ #_ #f #(n-1) (S.tail p) (idx / 2) (if idx % 2 = 0 then padded_hash_fun #_ f h (S.head p) else padded_hash_fun #_ f (S.head p) h) val mt_verify: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> p:(path #hsz n) -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> padded_hash #hsz -> GTot prop let mt_verify #hsz #f #n p idx h rt = rt == mt_verify_ #_ #f p idx h /// Correctness: the root of a tree is correctly recomputed from any of its paths val hs_next_lv_get: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> hs:hashes{S.length hs = 2 * n} -> idx:nat{idx < 2 * n} -> Lemma ((hs_next_lv #_ #f #n hs).[idx / 2] == (if idx % 2 = 0 then padded_hash_fun #_ f hs.[idx] hs.[idx + 1] else padded_hash_fun #_ f hs.[idx - 1] hs.[idx])) let rec hs_next_lv_get #hsz #f #n hs idx = if idx < 2 then () else hs_next_lv_get #_ #f #(n-1) (S.slice hs 2 (S.length hs)) (idx - 2) val mt_next_lv_get: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> Lemma ( (mt_next_lv #_ #f mt).[idx / 2] == (if idx % 2 = 0 then padded_hash_fun #_ f mt.[idx] mt.[idx + 1] else padded_hash_fun #_ f mt.[idx - 1] mt.[idx])) let mt_next_lv_get #hsz #f #n mt idx = hs_next_lv_get #_ #f #(pow2 (n-1)) mt idx val mt_get_path_ok_: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> t:merkle_tree #hsz n -> i:nat{i < pow2 n} -> Lemma (mt_verify_ #_ #f (mt_get_path #_ #f t i) i (mt_get t i) == mt_get_root #_ #f t) let rec mt_get_path_ok_ #hsz #f #n mt idx = if n = 0 then () else begin assert (S.head (mt_get_path #_ #f mt idx) == (if idx % 2 = 0 then mt.[idx + 1] else mt.[idx - 1])); assert (S.equal (S.tail (mt_get_path #_ #f mt idx)) (mt_get_path #_ #f (mt_next_lv #_ #f mt) (idx / 2))); mt_get_path_ok_ #_ #f (mt_next_lv #_ #f mt) (idx / 2); mt_next_lv_get #_ #f mt idx end /// Security: we reduce tree collisions to collisions on the hash /// compression function. Such collisions yield collisions on the SHA2 /// standard (by adding the same length and padding to the /// accumulators). /// /// One complication addressed in the proof is the handling of /// implicit padding. /// All hashes in a sequence are raw hashes, not padding val raw_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Tot Type0 (decreases (S.length hs)) let rec raw_hashes #hsz #f hs = if S.length hs = 0 then True else (HRaw? (S.head hs) /\ raw_hashes #_ #f (S.tail hs)) val raw_hashes_raws: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes{raw_hashes #hsz #f hs} -> Tot (S.seq (hash #hsz)) (decreases (S.length hs)) let rec raw_hashes_raws #hsz #f hs = if S.length hs = 0 then S.empty else S.cons (HRaw?.hr (S.head hs)) (raw_hashes_raws #_ #f (S.tail hs)) val raw_hashes_index: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat{i < S.length hs} -> Lemma (requires raw_hashes #_ #f hs) (ensures HRaw? #hsz hs.[i]) (decreases i) let rec raw_hashes_index #hsz #f hs i = if i = 0 then () else raw_hashes_index #_ #f (S.tail hs) (i - 1) val raw_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires raw_hashes #_ #f hs) (ensures raw_hashes #_ #f (S.slice hs i j)) (decreases (j - i)) let rec raw_hashes_slice #hsz #f hs i j = if i = j then () else ( raw_hashes_index #_ #f hs i; raw_hashes_slice #_ #f hs (i + 1) j) /// All hashes in a sequence are just padding val pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz ->
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "Spec.Agile.Hash.fsti.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "MerkleTree.Spec.fst" }
[ { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Seq", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "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": 1, "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": 10, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
hs: MerkleTree.Spec.hashes -> Type0
Prims.Tot
[ "total" ]
[]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.hashes", "FStar.Seq.Base.equal", "MerkleTree.Spec.padded_hash", "FStar.Seq.Base.create", "FStar.Seq.Base.length", "MerkleTree.Spec.HPad" ]
[]
false
false
false
false
true
let pad_hashes #hsz #f hs =
S.equal hs (S.create (S.length hs) HPad)
false
GradedMonad.fst
GradedMonad.put
val put (#s: _) (x: s) : st s monoid_nat_plus 1 unit
val put (#s: _) (x: s) : st s monoid_nat_plus 1 unit
let put #s (x:s) : st s monoid_nat_plus 1 unit = fun _ -> (), x
{ "file_name": "examples/typeclasses/GradedMonad.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 63, "end_line": 52, "start_col": 0, "start_line": 52 }
module GradedMonad (* NB: this is the old version of the graded monad that has a monoid index parameter everywhere instead of a constraint on the type. We keep it for CI purposes. See doc/book/code/GradedMonad.fst for better version. *) #set-options "--warn_error -350" //SNIPPET_START:monoid$ class monoid (a:Type) = { op : a -> a -> a; one : a; properties: squash ( (forall (x:a). op one x == x /\ op x one == x) /\ (forall (x y z:a). op x (op y z) == op (op x y) z) ); } instance monoid_nat_plus : monoid nat = { op = (fun (x y:nat) -> x + y); one = 0; properties = () } //SNIPPET_END: monoid$ class graded_monad (#index:Type) (m: monoid index -> index -> Type -> Type) = { return : #a:Type -> #im:monoid index -> x:a -> m im one a; bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index -> m im ia a -> (a -> m im ib b) -> m im (op ia ib) b } //we now have do notation for graded monads let st (s:Type) monoid_nat_plus (count:nat) (a:Type) = s -> a & s instance st_graded (s:Type) : graded_monad (st s) = { return = (fun #a #im (x:a) s -> x, s); bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s) } // A write-counting grade monad
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.Typeclasses.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "GradedMonad.fst" }
[ { "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
x: s -> GradedMonad.st s GradedMonad.monoid_nat_plus 1 Prims.unit
Prims.Tot
[ "total" ]
[]
[ "FStar.Pervasives.Native.Mktuple2", "Prims.unit", "FStar.Pervasives.Native.tuple2", "GradedMonad.st", "GradedMonad.monoid", "Prims.nat", "GradedMonad.monoid_nat_plus" ]
[]
false
false
false
false
false
let put #s (x: s) : st s monoid_nat_plus 1 unit =
fun _ -> (), x
false
GradedMonad.fst
GradedMonad.st_graded
[@@ FStar.Tactics.Typeclasses.tcinstance] val st_graded (s: Type) : graded_monad (st s)
[@@ FStar.Tactics.Typeclasses.tcinstance] val st_graded (s: Type) : graded_monad (st s)
instance st_graded (s:Type) : graded_monad (st s) = { return = (fun #a #im (x:a) s -> x, s); bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s) }
{ "file_name": "examples/typeclasses/GradedMonad.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 1, "end_line": 48, "start_col": 0, "start_line": 44 }
module GradedMonad (* NB: this is the old version of the graded monad that has a monoid index parameter everywhere instead of a constraint on the type. We keep it for CI purposes. See doc/book/code/GradedMonad.fst for better version. *) #set-options "--warn_error -350" //SNIPPET_START:monoid$ class monoid (a:Type) = { op : a -> a -> a; one : a; properties: squash ( (forall (x:a). op one x == x /\ op x one == x) /\ (forall (x y z:a). op x (op y z) == op (op x y) z) ); } instance monoid_nat_plus : monoid nat = { op = (fun (x y:nat) -> x + y); one = 0; properties = () } //SNIPPET_END: monoid$ class graded_monad (#index:Type) (m: monoid index -> index -> Type -> Type) = { return : #a:Type -> #im:monoid index -> x:a -> m im one a; bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index -> m im ia a -> (a -> m im ib b) -> m im (op ia ib) b } //we now have do notation for graded monads
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.Typeclasses.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "GradedMonad.fst" }
[ { "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
s: Type -> GradedMonad.graded_monad (GradedMonad.st s)
Prims.Tot
[ "total" ]
[]
[ "GradedMonad.Mkgraded_monad", "Prims.nat", "GradedMonad.monoid", "FStar.Pervasives.Native.tuple2", "FStar.Pervasives.Native.Mktuple2", "GradedMonad.graded_monad", "GradedMonad.st" ]
[]
false
false
false
true
false
[@@ FStar.Tactics.Typeclasses.tcinstance] let st_graded (s: Type) : graded_monad (st s) =
{ return = (fun #a #im (x: a) s -> x, s); bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s) }
false
GradedMonad.fst
GradedMonad.st
val st : s: Type -> monoid_nat_plus: _ -> count: Prims.nat -> a: Type -> Type
let st (s:Type) monoid_nat_plus (count:nat) (a:Type) = s -> a & s
{ "file_name": "examples/typeclasses/GradedMonad.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 65, "end_line": 43, "start_col": 0, "start_line": 43 }
module GradedMonad (* NB: this is the old version of the graded monad that has a monoid index parameter everywhere instead of a constraint on the type. We keep it for CI purposes. See doc/book/code/GradedMonad.fst for better version. *) #set-options "--warn_error -350" //SNIPPET_START:monoid$ class monoid (a:Type) = { op : a -> a -> a; one : a; properties: squash ( (forall (x:a). op one x == x /\ op x one == x) /\ (forall (x y z:a). op x (op y z) == op (op x y) z) ); } instance monoid_nat_plus : monoid nat = { op = (fun (x y:nat) -> x + y); one = 0; properties = () } //SNIPPET_END: monoid$ class graded_monad (#index:Type) (m: monoid index -> index -> Type -> Type) = { return : #a:Type -> #im:monoid index -> x:a -> m im one a; bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index -> m im ia a -> (a -> m im ib b) -> m im (op ia ib) b } //we now have do notation for graded monads
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.Typeclasses.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "GradedMonad.fst" }
[ { "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
s: Type -> monoid_nat_plus: _ -> count: Prims.nat -> a: Type -> Type
Prims.Tot
[ "total" ]
[]
[ "Prims.nat", "FStar.Pervasives.Native.tuple2" ]
[]
false
false
false
true
true
let st (s: Type) monoid_nat_plus (count: nat) (a: Type) =
s -> a & s
false
GradedMonad.fst
GradedMonad.test
val test : GradedMonad.st s GradedMonad.monoid_nat_plus (GradedMonad.op 0 1) Prims.unit
let test #s = x <-- get #s ; put x
{ "file_name": "examples/typeclasses/GradedMonad.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 7, "end_line": 56, "start_col": 0, "start_line": 54 }
module GradedMonad (* NB: this is the old version of the graded monad that has a monoid index parameter everywhere instead of a constraint on the type. We keep it for CI purposes. See doc/book/code/GradedMonad.fst for better version. *) #set-options "--warn_error -350" //SNIPPET_START:monoid$ class monoid (a:Type) = { op : a -> a -> a; one : a; properties: squash ( (forall (x:a). op one x == x /\ op x one == x) /\ (forall (x y z:a). op x (op y z) == op (op x y) z) ); } instance monoid_nat_plus : monoid nat = { op = (fun (x y:nat) -> x + y); one = 0; properties = () } //SNIPPET_END: monoid$ class graded_monad (#index:Type) (m: monoid index -> index -> Type -> Type) = { return : #a:Type -> #im:monoid index -> x:a -> m im one a; bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index -> m im ia a -> (a -> m im ib b) -> m im (op ia ib) b } //we now have do notation for graded monads let st (s:Type) monoid_nat_plus (count:nat) (a:Type) = s -> a & s instance st_graded (s:Type) : graded_monad (st s) = { return = (fun #a #im (x:a) s -> x, s); bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s) } // A write-counting grade monad let get #s : st s monoid_nat_plus 0 s = fun s -> s, s let put #s (x:s) : st s monoid_nat_plus 1 unit = fun _ -> (), x
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.Typeclasses.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "GradedMonad.fst" }
[ { "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
GradedMonad.st s GradedMonad.monoid_nat_plus (GradedMonad.op 0 1) Prims.unit
Prims.Tot
[ "total" ]
[]
[ "GradedMonad.bind", "Prims.nat", "GradedMonad.st", "GradedMonad.monoid", "GradedMonad.st_graded", "Prims.unit", "GradedMonad.monoid_nat_plus", "GradedMonad.get", "GradedMonad.put", "GradedMonad.op" ]
[]
false
false
false
false
false
let test #s =
x <-- get #s ; put x
false
GradedMonad.fst
GradedMonad.get
val get (#s: _) : st s monoid_nat_plus 0 s
val get (#s: _) : st s monoid_nat_plus 0 s
let get #s : st s monoid_nat_plus 0 s = fun s -> s, s
{ "file_name": "examples/typeclasses/GradedMonad.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 53, "end_line": 51, "start_col": 0, "start_line": 51 }
module GradedMonad (* NB: this is the old version of the graded monad that has a monoid index parameter everywhere instead of a constraint on the type. We keep it for CI purposes. See doc/book/code/GradedMonad.fst for better version. *) #set-options "--warn_error -350" //SNIPPET_START:monoid$ class monoid (a:Type) = { op : a -> a -> a; one : a; properties: squash ( (forall (x:a). op one x == x /\ op x one == x) /\ (forall (x y z:a). op x (op y z) == op (op x y) z) ); } instance monoid_nat_plus : monoid nat = { op = (fun (x y:nat) -> x + y); one = 0; properties = () } //SNIPPET_END: monoid$ class graded_monad (#index:Type) (m: monoid index -> index -> Type -> Type) = { return : #a:Type -> #im:monoid index -> x:a -> m im one a; bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index -> m im ia a -> (a -> m im ib b) -> m im (op ia ib) b } //we now have do notation for graded monads let st (s:Type) monoid_nat_plus (count:nat) (a:Type) = s -> a & s instance st_graded (s:Type) : graded_monad (st s) = { return = (fun #a #im (x:a) s -> x, s); bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s) }
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.Typeclasses.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked" ], "interface_file": false, "source_file": "GradedMonad.fst" }
[ { "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
GradedMonad.st s GradedMonad.monoid_nat_plus 0 s
Prims.Tot
[ "total" ]
[]
[ "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.tuple2", "GradedMonad.st", "GradedMonad.monoid", "Prims.nat", "GradedMonad.monoid_nat_plus" ]
[]
false
false
false
false
false
let get #s : st s monoid_nat_plus 0 s =
fun s -> s, s
false
MerkleTree.Spec.fst
MerkleTree.Spec.padded_hash_fun
val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)
val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)
let padded_hash_fun #hsz f lh rh = allow_inversion (padded_hash #hsz); match lh, rh with | HPad , _ -> HPad | _ , HPad -> lh | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "7d7bdc20f2033171e279c176b26e84f9069d23c6", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
{ "end_col": 42, "end_line": 42, "start_col": 0, "start_line": 37 }
module MerkleTree.Spec open FStar.Classical open FStar.Mul open FStar.Seq module S = FStar.Seq #set-options "--max_fuel 0 --max_ifuel 0 --z3rlimit 10" // For SHA2_256, this is is a sequence of 32 bytes // These are secret bytes, hence not an eqtype type hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz } type hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz) val sha256_compress: hash_fun_t #32 let sha256_compress src1 src2 = let sz = Spec.Hash.Definitions.SHA2_256 in let hash_alg = Spec.Hash.Definitions.SHA2_256 in let acc = Spec.Agile.Hash.init hash_alg in let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in Spec.Agile.Hash.finish hash_alg acc () /// For simplicity, we will specify the root for a sequence of [i] /// tags where [i <= 2^n] as the root of a full binary tree with [2^n] /// leaves obtained by padding the sequence with dummies. This /// requires extending the definitions of hashes and hash functions. Our /// extended definition of hash justifies skipping any concrete /// computation on dummies. noeq type padded_hash #hsz = | HRaw: hr:hash #hsz -> padded_hash #hsz | HPad // right padding to make the size of a Merkle tree a power of 2
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "Spec.Agile.Hash.fsti.checked", "prims.fst.checked", "FStar.StrongExcludedMiddle.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked", "FStar.Classical.fsti.checked" ], "interface_file": false, "source_file": "MerkleTree.Spec.fst" }
[ { "abbrev": true, "full_module": "FStar.Seq", "short_module": "S" }, { "abbrev": false, "full_module": "FStar.Seq", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "FStar.Classical", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "short_module": null }, { "abbrev": false, "full_module": "MerkleTree", "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": 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": 10, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
f: MerkleTree.Spec.hash_fun_t -> lh: MerkleTree.Spec.padded_hash -> rh: MerkleTree.Spec.padded_hash -> Prims.GTot MerkleTree.Spec.padded_hash
Prims.GTot
[ "sometrivial" ]
[]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.padded_hash", "FStar.Pervasives.Native.Mktuple2", "MerkleTree.Spec.HPad", "MerkleTree.Spec.hash", "MerkleTree.Spec.HRaw", "Prims.unit", "FStar.Pervasives.allow_inversion" ]
[]
false
false
false
false
false
let padded_hash_fun #hsz f lh rh =
allow_inversion (padded_hash #hsz); match lh, rh with | HPad, _ -> HPad | _, HPad -> lh | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)
false
Hacl.Spec.SHA2.Lemmas.fst
Hacl.Spec.SHA2.Lemmas.transpose_ws_lemma_ij
val transpose_ws_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l])
val transpose_ws_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l])
let transpose_ws_lemma_ij #a #m ws j i = assert (((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v (transpose_ws ws).[i]).[j]); match lanes a m with | 1 -> () | 4 -> transpose_ws4_lemma_ij #a #m ws j i | 8 -> transpose_ws8_lemma_ij #a #m ws j i
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "eb1badfa34c70b0bbe0fe24fe0f49fb1295c7872", "git_url": "https://github.com/project-everest/hacl-star.git", "project_name": "hacl-star" }
{ "end_col": 44, "end_line": 79, "start_col": 0, "start_line": 74 }
module Hacl.Spec.SHA2.Lemmas open FStar.Mul open Lib.IntTypes open Lib.Sequence open Lib.IntVector open Lib.IntVector.Transpose open Spec.Hash.Definitions open Hacl.Spec.SHA2.Vec #set-options "--z3rlimit 50 --fuel 0 --ifuel 1" val transpose_ws4_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16 -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws4_lemma_ij #a #m ws j i = let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs); //assert ((transpose_ws4 ws).[i] == (sub (transpose_ws4 ws) (i_sub * l) l).[j_sub]); //assert ((transpose_ws4 ws).[i] == (transpose4x4_lseq vs).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v (transpose4x4_lseq vs).[j_sub]).[j]); transpose4x4_lemma vs; assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v vs.[j]).[j_sub]); assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i_sub * l + j]).[j_sub]) val transpose_ws8_lemma_ij: #a:sha2_alg -> #m:m_spec{lanes a m == 8} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in (vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l]) let transpose_ws8_lemma_ij #a #m ws j i = let l = lanes a m in let i_sub = i / l in let j_sub = i % l in assert (i_sub * l + j_sub == i); let vs = sub ws (i_sub * l) l in eq_intro (sub (transpose_ws8 ws) (i_sub * l) l) (transpose8x8_lseq vs); assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v (transpose8x8_lseq vs).[j_sub]).[j]); transpose8x8_lemma vs; assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i_sub * lanes a m + j]).[j_sub]) val transpose_ws_lemma_ij: #a:sha2_alg -> #m:m_spec{is_supported a m} -> ws:ws_spec a m -> j:nat{j < lanes a m} -> i:nat{i < 16} -> Lemma (let l = lanes a m in ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l])
{ "checked_file": "/", "dependencies": [ "Spec.Hash.Definitions.fst.checked", "prims.fst.checked", "Lib.Sequence.fsti.checked", "Lib.IntVector.Transpose.fsti.checked", "Lib.IntVector.fsti.checked", "Lib.IntTypes.fsti.checked", "Hacl.Spec.SHA2.Vec.fst.checked", "FStar.Seq.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.Mul.fst.checked" ], "interface_file": false, "source_file": "Hacl.Spec.SHA2.Lemmas.fst" }
[ { "abbrev": false, "full_module": "Hacl.Spec.SHA2.Vec", "short_module": null }, { "abbrev": false, "full_module": "Spec.Hash.Definitions", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector.Transpose", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntVector", "short_module": null }, { "abbrev": false, "full_module": "Lib.Sequence", "short_module": null }, { "abbrev": false, "full_module": "Lib.IntTypes", "short_module": null }, { "abbrev": false, "full_module": "FStar.Mul", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "short_module": null }, { "abbrev": false, "full_module": "Hacl.Spec.SHA2", "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": 1, "max_fuel": 0, "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": false, "z3cliopt": [], "z3refresh": false, "z3rlimit": 50, "z3rlimit_factor": 1, "z3seed": 0, "z3smtopt": [], "z3version": "4.8.5" }
false
ws: Hacl.Spec.SHA2.Vec.ws_spec a m -> j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} -> i: Prims.nat{i < 16} -> FStar.Pervasives.Lemma (ensures (let l = Hacl.Spec.SHA2.Vec.lanes a m in (Hacl.Spec.SHA2.Vec.ws_spec_v (Hacl.Spec.SHA2.Vec.transpose_ws ws)).[ j ].[ i ] == (Lib.IntVector.vec_v ws.[ (i / l) * l + j ]).[ i % l ]))
FStar.Pervasives.Lemma
[ "lemma" ]
[]
[ "Spec.Hash.Definitions.sha2_alg", "Hacl.Spec.SHA2.Vec.m_spec", "Hacl.Spec.SHA2.Vec.is_supported", "Hacl.Spec.SHA2.Vec.ws_spec", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "Hacl.Spec.SHA2.Vec.lanes", "Hacl.Spec.SHA2.Lemmas.transpose_ws4_lemma_ij", "Hacl.Spec.SHA2.Lemmas.transpose_ws8_lemma_ij", "Prims.unit", "Prims._assert", "Prims.eq2", "Lib.IntTypes.uint_t", "Spec.Hash.Definitions.word_t", "Lib.IntTypes.SEC", "Prims.l_or", "Hacl.Spec.SHA2.Vec.word", "FStar.Seq.Base.index", "Lib.Sequence.to_seq", "Lib.Sequence.op_String_Access", "Lib.Sequence.lseq", "Hacl.Spec.SHA2.Vec.ws_spec_v", "Hacl.Spec.SHA2.Vec.transpose_ws", "Lib.IntVector.vec_v", "Hacl.Spec.SHA2.Vec.element_t" ]
[]
false
false
true
false
false
let transpose_ws_lemma_ij #a #m ws j i =
assert (((ws_spec_v (transpose_ws ws)).[ j ]).[ i ] == (vec_v (transpose_ws ws).[ i ]).[ j ]); match lanes a m with | 1 -> () | 4 -> transpose_ws4_lemma_ij #a #m ws j i | 8 -> transpose_ws8_lemma_ij #a #m ws j i
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.solve_mp
val solve_mp (#a: _) (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: (matching_solution -> Tac a)) : Tac a
val solve_mp (#a: _) (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: (matching_solution -> Tac a)) : Tac a
let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 62, "end_line": 485, "start_col": 0, "start_line": 474 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body``
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
problem: FStar.Tactics.PatternMatching.matching_problem -> hypotheses: Prims.list FStar.Tactics.PatternMatching.hypothesis -> goal: FStar.Tactics.NamedView.term -> body: (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a) -> FStar.Tactics.Effect.Tac a
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.matching_problem", "Prims.list", "FStar.Tactics.PatternMatching.hypothesis", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.solve_mp_for_hyps", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_hyps", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_goal", "FStar.Tactics.PatternMatching.Mkmatching_solution", "Prims.Nil", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.V2.Derived.fail", "Prims.string", "Prims.op_Hat", "FStar.Tactics.PatternMatching.string_of_match_exception", "FStar.Tactics.PatternMatching.bindings", "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.interp_pattern" ]
[]
false
true
false
false
false
let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: (matching_solution -> Tac a)) : Tac a =
let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.assoc_varname_fail
val assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b
val assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b
let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 15, "end_line": 398, "start_col": 0, "start_line": 394 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }"
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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.PatternMatching.varname -> ls: Prims.list (FStar.Tactics.PatternMatching.varname * b) -> FStar.Tactics.Effect.Tac b
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.varname", "Prims.list", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.assoc", "FStar.Tactics.V2.Derived.fail", "Prims.op_Hat" ]
[]
false
true
false
false
false
let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b =
match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.locate_fn_of_binder_kind
val locate_fn_of_binder_kind : binder_kind: FStar.Tactics.PatternMatching.abspat_binder_kind -> FStar.Stubs.Reflection.Types.term
let locate_fn_of_binder_kind binder_kind = match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 31, "end_line": 694, "start_col": 0, "start_line": 690 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body`` succeed. **) let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution (** Solve a matching problem. The solution returned is constructed to ensure that the continuation ``body`` succeeds: this implements the usual backtracking-match semantics. **) let solve_mp #a (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: matching_solution -> Tac a) : Tac a = let goal_ps = match problem.mp_goal with | None -> { ms_vars = []; ms_hyps = [] } | Some pat -> match interp_pattern pat goal with | Failure ex -> fail ("Failed to match goal: " ^ (string_of_match_exception ex)) | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps /// A DSL for pattern-matching /// ========================== /// /// Using pattern-matching problems as defined above is relatively cumbersome, /// so we now introduce a lightweight notation, in two steps: pattern notations, /// and matching-problem notations. /// /// Pattern notations /// ----------------- /// /// The first part of our pattern-matching syntax is pattern notations: we /// provide a reflective function which constructs a pattern from a term: /// variables are holes, free variables are constants, and applications are /// application patterns. (* FIXME: MOVE *) let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname (** Compile a term `tm` into a pattern. **) let rec pattern_of_term_ex tm : Tac (match_res pattern) = match inspect tm with | Tv_Var bv -> return (PVar (name_of_namedv bv)) | Tv_FVar fv | Tv_UInst fv _ -> let qn = fv_to_string fv in return (PQn qn) | Tv_Type _ -> return PType | Tv_App f (x, _) -> let? fpat = pattern_of_term_ex f in let? xpat = pattern_of_term_ex x in return (PApp fpat xpat) | _ -> raise (UnsupportedTermInPattern tm) (** β-reduce a term `tm`. This is useful to remove needles function applications introduced by F*, like ``(fun a b c -> a) 1 2 3``. **) let beta_reduce (tm: term) : Tac term = norm_term [] tm (** Compile a term `tm` into a pattern. **) let pattern_of_term tm : Tac pattern = match pattern_of_term_ex tm with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Problem notations /// ----------------- /// /// We then introduce a DSL for matching problems, best explained on the /// following example:: /// /// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④) /// /// This notation is intended to express a pattern-matching problems with three /// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``, /// and ``h3`` against pattern ② and the goal against the pattern ③. The body /// of the notation (④) is then run with appropriate terms bound to ``a``, /// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``, /// and ``()`` bound to ``g``. /// /// We call these patterns ``abspat``s (abstraction patterns), and we provide /// facilities to parse them into matching problems, and to run their bodies /// against a particular matching solution. // We used to annotate variables with an explicit 'var' marker, but then that // var annotation leaked into the types of other hypotheses due to type // inference, requiring non-trivial normalization. // let var (a: Type) = a let hyp (a: Type) = binding let pm_goal (a: Type) = unit let hyp_qn = `%hyp let goal_qn = `%pm_goal noeq type abspat_binder_kind = | ABKVar of typ | ABKHyp | ABKGoal let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal" noeq type abspat_argspec = { asa_name: absvar; asa_kind: abspat_binder_kind } // We must store this continuation, because recomputing it yields different // names when the binders are re-opened. type abspat_continuation = list abspat_argspec * term let type_of_named_binder (nb : binder) : term = nb.sort let classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) = let varname = "v" in let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in let goal_pat = PApp (PQn goal_qn) (PVar varname) in let typ = type_of_named_binder b in match interp_pattern hyp_pat typ with | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ | Success _ -> fail "classifiy_abspat_binder: impossible (1)" | Failure _ -> match interp_pattern goal_pat typ with | Success [(_, goal_typ)] -> ABKGoal, goal_typ | Success _ -> fail "classifiy_abspat_binder: impossible (2)" | Failure _ -> ABKVar typ, typ (** Split an abstraction `tm` into a list of binders and a body. **) let rec binders_and_body_of_abs tm : Tac (list binder * term) = match inspect tm with | Tv_Abs binder tm -> let binders, body = binders_and_body_of_abs tm in binder :: binders, body | _ -> [], tm let cleanup_abspat (t: term) : Tac term = norm_term [] t let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname (** Parse a notation into a matching problem and a continuation. Pattern-matching notations are of the form ``(fun binders… -> continuation)``, where ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``. ``var`` binders are typed holes to be used in other binders; ``hyp`` binders indicate a pattern to be matched against hypotheses; and ``goal`` binders match the goal. A reduction phase is run to ensure that the pattern looks reasonable; it is needed because F* tends to infer arguments in β-expanded form. The continuation returned can't directly be applied to a pattern-matching solution; see ``interp_abspat_continuation`` below for that. **) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) = let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in debug ("Got binders: " ^ (String.concat ", " (map (fun b -> name_of_named_binder b <: Tac string) binders))); let classified_binders : list (binder & string & abspat_binder_kind & typ) = map (fun binder -> let bv_name = name_of_named_binder binder in debug ("Got binder: " ^ bv_name ^ "; type is " ^ term_to_string (type_of_named_binder binder)); let binder_kind, typ = classify_abspat_binder binder in (binder, bv_name, binder_kind, typ)) binders in let problem = fold_left (fun problem (binder, bv_name, binder_kind, typ) -> debug ("Compiling binder " ^ name_of_named_binder binder ^ ", classified as " ^ string_of_abspat_binder_kind binder_kind ^ ", with type " ^ term_to_string typ); match binder_kind with | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars } | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ)) :: problem.mp_hyps } | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) }) ({ mp_vars = []; mp_hyps = []; mp_goal = None }) classified_binders in let continuation = let abspat_argspec_of_binder xx : Tac abspat_argspec = match xx with | (binder, xx, binder_kind, yy) -> { asa_name = binder_to_binding binder; asa_kind = binder_kind } in (map abspat_argspec_of_binder classified_binders, tm) in let mp = { mp_vars = List.Tot.Base.rev #varname problem.mp_vars; mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps; mp_goal = problem.mp_goal } in debug ("Got matching problem: " ^ (string_of_matching_problem mp)); mp, continuation /// Continuations /// ------------- /// /// Parsing an abspat yields a matching problem and a continuation of type /// ``abspat_continuation``, which is essentially just a list of binders and a /// term (the body of the abstraction pattern). (** Get the (quoted) type expected by a specific kind of abspat binder. **) let arg_type_of_binder_kind binder_kind : Tac term = match binder_kind with | ABKVar typ -> typ | ABKHyp -> `binder | ABKGoal -> `unit
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
binder_kind: FStar.Tactics.PatternMatching.abspat_binder_kind -> FStar.Stubs.Reflection.Types.term
Prims.Tot
[ "total" ]
[]
[ "FStar.Tactics.PatternMatching.abspat_binder_kind", "FStar.Stubs.Reflection.Types.typ", "FStar.Stubs.Reflection.Types.term" ]
[]
false
false
false
true
false
let locate_fn_of_binder_kind binder_kind =
match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.solve_mp_for_hyps
val solve_mp_for_hyps (#a: _) (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: (matching_solution -> Tac a)) (partial_solution: matching_solution) : Tac a
val solve_mp_for_hyps (#a: _) (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: (matching_solution -> Tac a)) (partial_solution: matching_solution) : Tac a
let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (partial_solution: matching_solution) : Tac a = match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 22, "end_line": 468, "start_col": 0, "start_line": 457 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of the pattern. Returns a result in the exception monad. **) let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm (** Match a pattern `pat` against a term. Returns a result in the exception monad. **) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) = fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings) (** Match a term `tm` against a pattern `pat`. Raises an exception if the match fails. This is mostly useful for debugging: use ``mgw`` to capture matches. **) let match_term pat (tm : term) : Tac bindings = match interp_pattern pat (norm_term [] tm) with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern-matching problems /// ========================= /// /// Generalizing past single-term single-pattern problems, we obtain the /// following notions of pattern-matching problems and solutions: let debug msg : Tac unit = () // print msg /// Definitions /// ----------- let absvar = binding type hypothesis = binding /// A matching problem is composed of holes (``mp_vars``), hypothesis patterns /// (``mp_hyps``), and a goal pattern (``mp_goal``). noeq type matching_problem = { mp_vars: list varname; mp_hyps: list (varname * pattern); mp_goal: option pattern } let string_of_matching_problem mp = let vars = String.concat ", " mp.mp_vars in let hyps = String.concat "\n " (List.Tot.Base.map (fun (nm, pat) -> nm ^ ": " ^ (string_of_pattern pat)) mp.mp_hyps) in let goal = match mp.mp_goal with | None -> "_" | Some pat -> string_of_pattern pat in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ "\n" ^ " goal: " ^ goal ^ " }" /// A solution is composed of terms captured to mach the holes, and binders /// captured to match hypothesis patterns. noeq type matching_solution = { ms_vars: list (varname * term); ms_hyps: list (varname * hypothesis) } let string_of_matching_solution ms = let vars = String.concat "\n " (map (fun (varname, tm) -> varname ^ ": " ^ (term_to_string tm)) ms.ms_vars) in let hyps = String.concat "\n " (map (fun (nm, binding) -> nm ^ ": " ^ (binding_to_string binding)) ms.ms_hyps) in "\n{ vars: " ^ vars ^ "\n" ^ " hyps: " ^ hyps ^ " }" (** Find a varname in an association list; fail if it can't be found. **) let assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b = match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars) let ms_locate_unit (a: Type) _solution _binder_name : Tac unit = () /// Resolution /// ---------- /// /// Solving a matching problem is a two-steps process: find an initial /// assignment for holes based on the goal pattern, then find a set of /// hypotheses matching hypothesis patterns. /// /// Note that the implementation takes a continuation of type /// ``matching_solution -> Tac a``. This continuation is needed because we want /// users to be able to provide extra criteria on matching solutions (most /// commonly, this criterion is that a particular tactic should run /// successfuly). /// /// This makes it easy to implement a simple for of search through the context, /// where one can find a hypothesis matching a particular predicate by /// constructing a trivial matching problem and passing the predicate as the /// continuation. (** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed. ``name`` is used to refer to the hypothesis matched in the final solution. ``part_sol`` includes bindings gathered while matching previous solutions. **) let rec solve_mp_for_single_hyp #a (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: matching_solution -> Tac a) (part_sol: matching_solution) : Tac a = match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else // Must be in ``Tac`` here to run `body` (fun () -> match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with | Failure ex -> fail ("Failed to match hyp: " ^ (string_of_match_exception ex)) | Success bindings -> let ms_hyps = (name, h) :: part_sol.ms_hyps in body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps })) (fun () -> solve_mp_for_single_hyp name pat hs body part_sol) (** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
mp_hyps: Prims.list (FStar.Tactics.PatternMatching.varname * FStar.Tactics.PatternMatching.pattern) -> hypotheses: Prims.list FStar.Tactics.PatternMatching.hypothesis -> body: (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a) -> partial_solution: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a
FStar.Tactics.Effect.Tac
[]
[]
[ "Prims.list", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.hypothesis", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.solve_mp_for_single_hyp", "FStar.Tactics.PatternMatching.solve_mp_for_hyps" ]
[ "recursion" ]
false
true
false
false
false
let rec solve_mp_for_hyps #a (mp_hyps: list (varname * pattern)) (hypotheses: list hypothesis) (body: (matching_solution -> Tac a)) (partial_solution: matching_solution) : Tac a =
match mp_hyps with | [] -> body partial_solution | (name, pat) :: pats -> solve_mp_for_single_hyp name pat hypotheses (solve_mp_for_hyps pats hypotheses body) partial_solution
false
FStar.Tactics.PatternMatching.fst
FStar.Tactics.PatternMatching.interp_pattern_aux
val interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm: term) : Tac (match_res bindings)
val interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm: term) : Tac (match_res bindings)
let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term) : Tac (match_res bindings) = let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "10183ea187da8e8c426b799df6c825e24c0767d3", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
{ "end_col": 62, "end_line": 321, "start_col": 0, "start_line": 292 }
(* Copyright 2008-2018 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. *) /// ========================== /// Pattern-matching tactics /// ========================== /// /// :Author: Clément Pit-Claudel /// :Contact: [email protected] /// :Date: 2017-10-13 module FStar.Tactics.PatternMatching open FStar.Tactics.V2 /// Contents /// ======== /// /// 1 Contents /// 2 Motivation /// 3 Some utility functions /// 4 Pattern types /// 5 Pattern matching exceptions /// 5.1 Types of exceptions /// 5.2 The exception monad /// 5.3 Liftings /// 6 Pattern interpretation /// 7 Pattern-matching problems /// 7.1 Definitions /// 7.2 Resolution /// 8 A DSL for pattern-matching /// 8.1 Pattern notations /// 8.2 Problem notations /// 8.3 Continuations /// 9 Putting it all together /// 10 Examples /// 10.1 Simple examples /// 10.2 A real-life example /// 11 Possible extensions /// 12 Notes /// /// Motivation /// ========== /// /// Suppose you have a goal of the form ``squash (a == b)``. How do you capture /// `a` and `b` for further inspection? /// /// Here's a basic (but cumbersome!) implementation: let fetch_eq_side () : Tac (term * term) = let g = cur_goal () in match inspect g with | Tv_App squash (g, _) -> (match inspect squash with | Tv_UInst squash _ | Tv_FVar squash -> if fv_to_string squash = flatten_name squash_qn then (match inspect g with | Tv_App eq_type_x (y, _) -> (match inspect eq_type_x with | Tv_App eq_type (x, _) -> (match inspect eq_type with | Tv_App eq (typ, _) -> (match inspect eq with | Tv_UInst eq _ | Tv_FVar eq -> if fv_to_string eq = flatten_name eq2_qn then (x, y) else fail "not an equality" | _ -> fail "not an app2 of fvar: ") | _ -> fail "not an app3") | _ -> fail "not an app2") | _ -> fail "not an app under squash") else fail "not a squash" | _ -> fail "not an app of fvar at top level") | _ -> fail "not an app at top level" /// …and here's how you could use it: (* let _ = *) (* assert_by_tactic (1 + 1 == 2) *) (* (fun () -> let l, r = fetch_eq_side () in *) (* print (term_to_string l ^ " / " ^ term_to_string r)) *) /// This file defines pattern-matching primitives that let you write the same /// thing like this… /// /// .. code:: fstar /// /// let fetch_eq_side' #a () : Tac (term * term) = /// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) -> /// (quote left, quote right) <: Tac (term * term)) /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (fun () -> let l, r = fetch_eq_side' #int () in /// print (term_to_string l ^ " / " ^ term_to_string r)) /// /// …or, more succinctly, like this: /// /// .. code:: fstar /// /// let _ = /// assert_by_tactic (1 + 1 == 2) /// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) -> /// let l, r = quote left, quote right in /// print (term_to_string l ^ " / " ^ term_to_string r) <: Tac unit)) /// Some utility functions /// ====================== /// /// (Skip over this part on a quick read — these are just convenience functions) (** Ensure that tactic `t` fails. **) let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> () /// The following two tactics are needed because of issues with the ``Tac`` /// effect. let implies_intro' () : Tac unit = let _ = implies_intro () in () let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in () let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h (** Use a hypothesis at type a to satisfy a goal at type squash a *) let exact_hyp (a: Type0) (h: namedv) : Tac unit = let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)]) (** Use a hypothesis h (of type a) to satisfy a goal at type a *) let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h)) /// Pattern types /// ============= /// /// Patterns are defined using a simple inductive type, mirroring the structure /// of ``term_view``. type varname = string type qn = string type pattern = | PVar: name: varname -> pattern | PQn: qn: qn -> pattern | PType: pattern | PApp: hd: pattern -> arg: pattern -> pattern let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application" let rec string_of_pattern = function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")" /// Pattern matching exceptions /// =========================== /// /// Pattern-matching is defined as a pure, monadic function (because of issues /// with combining DM4F effects, but also because it helps with debugging). /// This section defines the exception monad. /// /// Types of exceptions /// ------------------- noeq type match_exception = | NameMismatch of qn * qn | SimpleMismatch of pattern * term | NonLinearMismatch of varname * term * term | UnsupportedTermInPattern of term | IncorrectTypeInAbsPatBinder of typ let term_head t : Tac string = match inspect t with | Tv_Var bv -> "Tv_Var" | Tv_BVar fv -> "Tv_BVar" | Tv_FVar fv -> "Tv_FVar" | Tv_UInst _ _ -> "Tv_UInst" | Tv_App f x -> "Tv_App" | Tv_Abs x t -> "Tv_Abs" | Tv_Arrow x t -> "Tv_Arrow" | Tv_Type _ -> "Tv_Type" | Tv_Refine x t -> "Tv_Refine" | Tv_Const cst -> "Tv_Const" | Tv_Uvar i t -> "Tv_Uvar" | Tv_Let r attrs b t1 t2 -> "Tv_Let" | Tv_Match t _ branches -> "Tv_Match" | Tv_AscribedT _ _ _ _ -> "Tv_AscribedT" | Tv_AscribedC _ _ _ _ -> "Tv_AscribedC" | Tv_Unknown -> "Tv_Unknown" | Tv_Unsupp -> "Tv_Unsupp" let string_of_match_exception = function | NameMismatch (qn1, qn2) -> "Match failure (name mismatch): expecting " ^ qn1 ^ ", found " ^ qn2 | SimpleMismatch (pat, tm) -> "Match failure (sort mismatch): expecting " ^ desc_of_pattern pat ^ ", got " ^ term_to_string tm | NonLinearMismatch (nm, t1, t2) -> "Match failure (nonlinear mismatch): variable " ^ nm ^ " needs to match both " ^ (term_to_string t1) ^ " and " ^ (term_to_string t2) | UnsupportedTermInPattern tm -> "Match failure (unsupported term in pattern): " ^ term_to_string tm ^ " (" ^ term_head tm ^ ")" | IncorrectTypeInAbsPatBinder typ -> "Incorrect type in pattern-matching binder: " ^ term_to_string typ ^ " (use one of ``var``, ``hyp …``, or ``goal …``)" /// The exception monad /// ------------------- noeq type match_res a = | Success of a | Failure of match_exception let return #a (x: a) : match_res a = Success x let (let?) (#a #b: Type) (f: match_res a) (g: a -> Tac (match_res b)) : Tac (match_res b) = match f with | Success aa -> g aa | Failure ex -> Failure ex let raise #a (ex: match_exception) : match_res a = Failure ex /// Liftings /// -------- /// /// There's a natural lifting from the exception monad into the tactic effect: let lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) let lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b = match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex) /// Pattern interpretation /// ====================== /// /// This section implement pattern-matching. This is strictly a one term, one /// pattern implementation — handling cases in which mutliple hypotheses match /// the same pattern is done later. type bindings = list (varname * term) let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings) (** Match a pattern against a term. `cur_bindings` is a list of bindings collected while matching previous parts of
{ "checked_file": "/", "dependencies": [ "prims.fst.checked", "FStar.Tactics.V2.fst.checked", "FStar.Tactics.fst.checked", "FStar.String.fsti.checked", "FStar.Squash.fsti.checked", "FStar.Pervasives.Native.fst.checked", "FStar.Pervasives.fsti.checked", "FStar.List.Tot.Base.fst.checked", "FStar.List.Tot.fst.checked", "FStar.List.fst.checked" ], "interface_file": false, "source_file": "FStar.Tactics.PatternMatching.fst" }
[ { "abbrev": false, "full_module": "FStar.Tactics.V2", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "short_module": null }, { "abbrev": false, "full_module": "FStar.Tactics", "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
pat: FStar.Tactics.PatternMatching.pattern -> cur_bindings: FStar.Tactics.PatternMatching.bindings -> tm: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.match_res FStar.Tactics.PatternMatching.bindings)
FStar.Tactics.Effect.Tac
[]
[]
[ "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.bindings", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.qn", "Prims.precedes", "FStar.Stubs.Reflection.Types.term", "FStar.Stubs.Reflection.V2.Data.aqualv", "FStar.Tactics.PatternMatching.op_let_Question", "FStar.Tactics.PatternMatching.return", "FStar.Tactics.PatternMatching.interp_pattern_aux", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.PatternMatching.raise", "FStar.Tactics.PatternMatching.SimpleMismatch", "FStar.Pervasives.Native.Mktuple2", "FStar.Tactics.NamedView.inspect", "FStar.Tactics.NamedView.universe", "FStar.Stubs.Reflection.Types.fv", "FStar.Stubs.Reflection.V2.Data.universes", "Prims.op_Equality", "Prims.string", "FStar.Reflection.V2.Derived.fv_to_string", "Prims.bool", "FStar.Tactics.PatternMatching.NameMismatch", "Prims.list", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.assoc", "FStar.Stubs.Reflection.V2.Builtins.term_eq", "FStar.Tactics.PatternMatching.NonLinearMismatch", "FStar.Pervasives.Native.Mktuple3", "Prims.Cons" ]
[ "recursion" ]
false
true
false
false
false
let rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm: term) : Tac (match_res bindings) =
let interp_var (v: varname) cur_bindings tm = match List.Tot.Base.assoc v cur_bindings with | Some tm' -> if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm')) | None -> return ((v, tm) :: cur_bindings) in let interp_qn (qn: qn) cur_bindings tm = match inspect tm with | Tv_UInst fv _ | Tv_FVar fv -> if fv_to_string fv = qn then return cur_bindings else raise (NameMismatch (qn, (fv_to_string fv))) | _ -> raise (SimpleMismatch (pat, tm)) in let interp_type cur_bindings tm = match inspect tm with | Tv_Type _ -> return cur_bindings | _ -> raise (SimpleMismatch (pat, tm)) in let interp_app (p_hd: (p: pattern{p << pat})) (p_arg: (p: pattern{p << pat})) cur_bindings tm = match inspect tm with | Tv_App hd (arg, _) -> let? with_hd = interp_pattern_aux p_hd cur_bindings hd in let? with_arg = interp_pattern_aux p_arg with_hd arg in return with_arg | _ -> raise (SimpleMismatch (pat, tm)) in match pat with | PVar var -> interp_var var cur_bindings tm | PQn qn -> interp_qn qn cur_bindings tm | PType -> interp_type cur_bindings tm | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm
false