effect
stringclasses
48 values
original_source_type
stringlengths
0
23k
opens_and_abbrevs
listlengths
2
92
isa_cross_project_example
bool
1 class
source_definition
stringlengths
9
57.9k
partial_definition
stringlengths
7
23.3k
is_div
bool
2 classes
is_type
null
is_proof
bool
2 classes
completed_definiton
stringlengths
1
250k
dependencies
dict
effect_flags
sequencelengths
0
2
ideal_premises
sequencelengths
0
236
mutual_with
sequencelengths
0
11
file_context
stringlengths
0
407k
interleaved
bool
1 class
is_simply_typed
bool
2 classes
file_name
stringlengths
5
48
vconfig
dict
is_simple_lemma
null
source_type
stringlengths
10
23k
proof_features
sequencelengths
0
1
name
stringlengths
8
95
source
dict
verbose_type
stringlengths
1
7.42k
source_range
dict
Prims.Tot
val aes128_key_expansion : normal lowstar_key128_t
[ { "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 } ]
false
let aes128_key_expansion //: normal lowstar_key128_t = as_normal_t #lowstar_key128_t lowstar_key128
val aes128_key_expansion : normal lowstar_key128_t let aes128_key_expansion =
false
null
false
as_normal_t #lowstar_key128_t lowstar_key128
{ "checked_file": "Vale.Stdcalls.X64.Aes.fst.checked", "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" }
[ "total" ]
[ "Vale.Stdcalls.X64.Aes.as_normal_t", "Vale.Stdcalls.X64.Aes.lowstar_key128_t", "Vale.Stdcalls.X64.Aes.lowstar_key128" ]
[]
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))
false
true
Vale.Stdcalls.X64.Aes.fst
{ "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" }
null
val aes128_key_expansion : normal lowstar_key128_t
[]
Vale.Stdcalls.X64.Aes.aes128_key_expansion
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
Vale.Interop.Base.normal Vale.Stdcalls.X64.Aes.lowstar_key128_t
{ "end_col": 48, "end_line": 31, "start_col": 4, "start_line": 31 }
Prims.Tot
val aes256_key_expansion : normal lowstar_key256_t
[ { "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 } ]
false
let aes256_key_expansion //: normal lowstar_key256_t = as_normal_t #lowstar_key256_t lowstar_key256
val aes256_key_expansion : normal lowstar_key256_t let aes256_key_expansion =
false
null
false
as_normal_t #lowstar_key256_t lowstar_key256
{ "checked_file": "Vale.Stdcalls.X64.Aes.fst.checked", "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" }
[ "total" ]
[ "Vale.Stdcalls.X64.Aes.as_normal_t", "Vale.Stdcalls.X64.Aes.lowstar_key256_t", "Vale.Stdcalls.X64.Aes.lowstar_key256" ]
[]
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))
false
true
Vale.Stdcalls.X64.Aes.fst
{ "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" }
null
val aes256_key_expansion : normal lowstar_key256_t
[]
Vale.Stdcalls.X64.Aes.aes256_key_expansion
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
Vale.Interop.Base.normal Vale.Stdcalls.X64.Aes.lowstar_key256_t
{ "end_col": 48, "end_line": 41, "start_col": 4, "start_line": 41 }
Prims.Tot
val lowstar_key128:lowstar_key128_t
[ { "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 } ]
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))
val lowstar_key128:lowstar_key128_t let lowstar_key128:lowstar_key128_t =
false
null
false
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": "Vale.Stdcalls.X64.Aes.fst.checked", "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" }
[ "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" ]
[]
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
false
true
Vale.Stdcalls.X64.Aes.fst
{ "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" }
null
val lowstar_key128:lowstar_key128_t
[]
Vale.Stdcalls.X64.Aes.lowstar_key128
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
Vale.Stdcalls.X64.Aes.lowstar_key128_t
{ "end_col": 74, "end_line": 28, "start_col": 2, "start_line": 24 }
Prims.Tot
val lowstar_key256:lowstar_key256_t
[ { "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 } ]
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))
val lowstar_key256:lowstar_key256_t let lowstar_key256:lowstar_key256_t =
false
null
false
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": "Vale.Stdcalls.X64.Aes.fst.checked", "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" }
[ "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" ]
[]
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
false
true
Vale.Stdcalls.X64.Aes.fst
{ "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" }
null
val lowstar_key256:lowstar_key256_t
[]
Vale.Stdcalls.X64.Aes.lowstar_key256
{ "file_name": "vale/code/arch/x64/interop/Vale.Stdcalls.X64.Aes.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
Vale.Stdcalls.X64.Aes.lowstar_key256_t
{ "end_col": 74, "end_line": 38, "start_col": 2, "start_line": 34 }
FStar.Tactics.Effect.Tac
val check_prop_validity (g: env) (p: term) (typing: tot_typing g p tm_prop) : T.Tac (prop_validity g p)
[ { "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 } ]
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
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) =
true
null
false
Pulse.Checker.Pure.check_prop_validity g p typing
{ "checked_file": "Pulse.Checker.IntroPure.fst.checked", "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" }
[]
[ "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" ]
[]
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))
false
false
Pulse.Checker.IntroPure.fst
{ "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" }
null
val check_prop_validity (g: env) (p: term) (typing: tot_typing g p tm_prop) : T.Tac (prop_validity g p)
[]
Pulse.Checker.IntroPure.check_prop_validity
{ "file_name": "lib/steel/pulse/Pulse.Checker.IntroPure.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
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)
{ "end_col": 53, "end_line": 28, "start_col": 4, "start_line": 28 }
FStar.Tactics.Effect.Tac
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)
[ { "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 } ]
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 } = 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
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) =
true
null
false
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
{ "checked_file": "Pulse.Checker.IntroPure.fst.checked", "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" }
[]
[ "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" ]
[]
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 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 })
false
false
Pulse.Checker.IntroPure.fst
{ "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" }
null
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)
[]
Pulse.Checker.IntroPure.check
{ "file_name": "lib/steel/pulse/Pulse.Checker.IntroPure.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
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)
{ "end_col": 125, "end_line": 46, "start_col": 46, "start_line": 38 }
FStar.Tactics.Effect.Tac
val check_prop (g: env) (p: term) : T.Tac (p: term & tot_typing g p tm_prop)
[ { "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 } ]
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))
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) =
true
null
false
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": "Pulse.Checker.IntroPure.fst.checked", "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" }
[]
[ "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" ]
[]
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
false
false
Pulse.Checker.IntroPure.fst
{ "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" }
null
val check_prop (g: env) (p: term) : T.Tac (p: term & tot_typing g p tm_prop)
[]
Pulse.Checker.IntroPure.check_prop
{ "file_name": "lib/steel/pulse/Pulse.Checker.IntroPure.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
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))
{ "end_col": 30, "end_line": 25, "start_col": 45, "start_line": 12 }
FStar.Pervasives.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))
[ { "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 } ]
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
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 =
false
null
true
let l = lanes a m in let ind = 8 * j + i / word_length a in let r0 = transpose8x8_lseq st in transpose8x8_lemma st
{ "checked_file": "Hacl.Spec.SHA2.Lemmas.fst.checked", "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" }
[ "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" ]
[]
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))
false
false
Hacl.Spec.SHA2.Lemmas.fst
{ "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" }
null
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))
[]
Hacl.Spec.SHA2.Lemmas.transpose_state8_lemma
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
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)))
{ "end_col": 23, "end_line": 117, "start_col": 41, "start_line": 113 }
FStar.Pervasives.Lemma
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)))
[ { "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 } ]
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
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 =
false
null
true
match lanes a m with | 1 -> () | 4 -> transpose_state4_lemma #a #m st j i | 8 -> transpose_state8_lemma #a #m st j i
{ "checked_file": "Hacl.Spec.SHA2.Lemmas.fst.checked", "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" }
[ "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" ]
[]
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)))
false
false
Hacl.Spec.SHA2.Lemmas.fst
{ "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" }
null
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)))
[]
Hacl.Spec.SHA2.Lemmas.transpose_state_lemma_ij
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
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)))
{ "end_col": 44, "end_line": 136, "start_col": 2, "start_line": 133 }
FStar.Pervasives.Lemma
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])
[ { "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 } ]
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 ((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_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 =
false
null
true
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 ])
{ "checked_file": "Hacl.Spec.SHA2.Lemmas.fst.checked", "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" }
[ "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" ]
[]
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])
false
false
Hacl.Spec.SHA2.Lemmas.fst
{ "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" }
null
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])
[]
Hacl.Spec.SHA2.Lemmas.transpose_ws4_lemma_ij
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
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 ]))
{ "end_col": 83, "end_line": 38, "start_col": 41, "start_line": 25 }
FStar.Pervasives.Lemma
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])
[ { "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 } ]
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
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 =
false
null
true
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
{ "checked_file": "Hacl.Spec.SHA2.Lemmas.fst.checked", "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" }
[ "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" ]
[]
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])
false
false
Hacl.Spec.SHA2.Lemmas.fst
{ "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" }
null
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])
[]
Hacl.Spec.SHA2.Lemmas.transpose_ws_lemma_ij
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
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 ]))
{ "end_col": 44, "end_line": 79, "start_col": 2, "start_line": 75 }
FStar.Pervasives.Lemma
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])
[ { "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 } ]
false
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_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 =
false
null
true
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 ])
{ "checked_file": "Hacl.Spec.SHA2.Lemmas.fst.checked", "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" }
[ "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_ws8", "Prims.unit", "Lib.IntVector.Transpose.transpose8x8_lemma", "Lib.IntVector.vec_t", "Lib.IntVector.Transpose.transpose8x8_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" ]
[]
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])
false
false
Hacl.Spec.SHA2.Lemmas.fst
{ "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" }
null
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])
[]
Hacl.Spec.SHA2.Lemmas.transpose_ws8_lemma_ij
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
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_ws8 ws).[ i ]).[ j ] == (Lib.IntVector.vec_v ws.[ (i / l) * l + j ]).[ i % l ]))
{ "end_col": 91, "end_line": 61, "start_col": 41, "start_line": 51 }
FStar.Pervasives.Lemma
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))
[ { "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 } ]
false
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_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 =
false
null
true
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)
{ "checked_file": "Hacl.Spec.SHA2.Lemmas.fst.checked", "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" }
[ "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.transpose4x4_lemma", "Spec.Hash.Definitions.word_t", "Lib.Sequence.sub", "Hacl.Spec.SHA2.Vec.element_t", "Lib.Sequence.lseq", "Lib.IntVector.vec_t", "Lib.IntVector.Transpose.transpose4x4_lseq", "Prims.unit" ]
[]
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))
false
false
Hacl.Spec.SHA2.Lemmas.fst
{ "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" }
null
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))
[]
Hacl.Spec.SHA2.Lemmas.transpose_state4_lemma
{ "file_name": "code/sha2-mb/Hacl.Spec.SHA2.Lemmas.fst", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
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)))
{ "end_col": 33, "end_line": 98, "start_col": 41, "start_line": 94 }
Prims.Tot
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "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 } ]
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 let opened = elab_term (comp_inames c) in if C_STAtomic? c then mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else let _ = assert (C_STGhost? c) in mk_frame_stt_ghost u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e
let elab_frame (c: comp_st) (frame: term) (e: R.term) =
false
null
false
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 let opened = elab_term (comp_inames c) in if C_STAtomic? c then mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else let _ = assert (C_STGhost? c) in mk_frame_stt_ghost u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e
{ "checked_file": "Pulse.Elaborate.Core.fst.checked", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.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" }
[ "total" ]
[ "Pulse.Syntax.Base.comp_st", "Pulse.Syntax.Base.term", "FStar.Reflection.Types.term", "Pulse.Syntax.Base.uu___is_C_ST", "Pulse.Reflection.Util.mk_frame_stt", "Pulse.Reflection.Util.mk_abs", "FStar.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.Reflection.Util.mk_frame_stt_ghost", "Prims.unit", "Prims._assert", "Prims.b2t", "Pulse.Syntax.Base.uu___is_C_STGhost", "Pulse.Syntax.Base.comp_inames", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.comp_pre", "Pulse.Syntax.Base.comp_res", "Pulse.Syntax.Base.universe", "Pulse.Syntax.Base.comp_u" ]
[]
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 open Pulse.Reflection.Util
false
true
Pulse.Elaborate.Core.fst
{ "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" }
null
val elab_frame : c: Pulse.Syntax.Base.comp_st -> frame: Pulse.Syntax.Base.term -> e: FStar.Reflection.Types.term -> FStar.Reflection.Types.term
[]
Pulse.Elaborate.Core.elab_frame
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
c: Pulse.Syntax.Base.comp_st -> frame: Pulse.Syntax.Base.term -> e: FStar.Reflection.Types.term -> FStar.Reflection.Types.term
{ "end_col": 96, "end_line": 24, "start_col": 52, "start_line": 13 }
Prims.Tot
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "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 } ]
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 let opened = elab_term (comp_inames c1) in if C_STAtomic? c1 then mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else let _ = assert (C_STGhost? c1) in mk_sub_stt_ghost u ty opened pre1 pre2 post1 post2 e
let elab_sub (c1 c2: comp_st) (e: R.term) =
false
null
false
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 let opened = elab_term (comp_inames c1) in if C_STAtomic? c1 then mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else let _ = assert (C_STGhost? c1) in mk_sub_stt_ghost u ty opened pre1 pre2 post1 post2 e
{ "checked_file": "Pulse.Elaborate.Core.fst.checked", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.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" }
[ "total" ]
[ "Pulse.Syntax.Base.comp_st", "FStar.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.Reflection.Util.mk_sub_stt_ghost", "Prims.unit", "Prims._assert", "Prims.b2t", "Pulse.Syntax.Base.uu___is_C_STGhost", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_inames", "Pulse.Reflection.Util.mk_abs", "FStar.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" ]
[]
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 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 let opened = elab_term (comp_inames c) in if C_STAtomic? c then mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else let _ = assert (C_STGhost? c) in mk_frame_stt_ghost u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e
false
true
Pulse.Elaborate.Core.fst
{ "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" }
null
val elab_sub : c1: Pulse.Syntax.Base.comp_st -> c2: Pulse.Syntax.Base.comp_st -> e: FStar.Reflection.Types.term -> FStar.Reflection.Types.term
[]
Pulse.Elaborate.Core.elab_sub
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
c1: Pulse.Syntax.Base.comp_st -> c2: Pulse.Syntax.Base.comp_st -> e: FStar.Reflection.Types.term -> FStar.Reflection.Types.term
{ "end_col": 64, "end_line": 39, "start_col": 41, "start_line": 26 }
Prims.Tot
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "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 } ]
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 })
let intro_pure_tm (p: term) =
false
null
false
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": "Pulse.Elaborate.Core.fst.checked", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.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" }
[ "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" ]
[]
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 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 let opened = elab_term (comp_inames c) in if C_STAtomic? c then mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else let _ = assert (C_STGhost? c) in mk_frame_stt_ghost u ty opened 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 let opened = elab_term (comp_inames c1) in if C_STAtomic? c1 then mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else let _ = assert (C_STGhost? c1) in mk_sub_stt_ghost u ty opened 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 bc with | Bind_comp _ _ _ _ _ _ _ -> if C_ST? c1 then 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 else mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 | Bind_comp_ghost_l _ _ _ _ (| reveal_a, reveal_a_typing |) _ _ _ -> mk_bind_ghost_atomic (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_a) | Bind_comp_ghost_r _ _ _ _ (| reveal_b, reveal_b_typing |) _ _ _ -> mk_bind_atomic_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_b) 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_STGhost_STAtomic _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_atomic (comp_u c1) t (elab_term (comp_inames c1)) (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a)
false
true
Pulse.Elaborate.Core.fst
{ "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" }
null
val intro_pure_tm : p: Pulse.Syntax.Base.term -> Pulse.Syntax.Base.st_term
[]
Pulse.Elaborate.Core.intro_pure_tm
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
p: Pulse.Syntax.Base.term -> Pulse.Syntax.Base.st_term
{ "end_col": 47, "end_line": 127, "start_col": 2, "start_line": 119 }
Prims.Tot
val elab_lift (#g #c1 #c2: _) (d: lift_comp g c1 c2) (e: R.term) : Tot R.term
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "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 } ]
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_STGhost_STAtomic _ _ (| reveal_a, reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_atomic (comp_u c1) t (elab_term (comp_inames c1)) (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a)
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 =
false
null
false
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_STGhost_STAtomic _ _ (| reveal_a , reveal_a_typing |) -> let t = elab_term (comp_res c1) in mk_lift_ghost_atomic (comp_u c1) t (elab_term (comp_inames c1)) (elab_term (comp_pre c1)) (mk_abs t R.Q_Explicit (elab_term (comp_post c1))) e (elab_term reveal_a)
{ "checked_file": "Pulse.Elaborate.Core.fst.checked", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.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" }
[ "total" ]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.comp", "Pulse.Typing.lift_comp", "FStar.Reflection.Types.term", "Pulse.Syntax.Base.comp_st", "Prims.l_and", "Prims.b2t", "Pulse.Syntax.Base.uu___is_C_STAtomic", "Prims.eq2", "Pulse.Syntax.Base.term", "Pulse.Syntax.Base.comp_inames", "Pulse.Syntax.Base.tm_emp_inames", "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.Reflection.V2.Data.Q_Explicit", "Pulse.Syntax.Base.comp_post", "Pulse.Syntax.Base.uu___is_C_STGhost", "Pulse.Typing.tot_typing", "Pulse.Typing.non_informative_witness_t", "Pulse.Reflection.Util.mk_lift_ghost_atomic", "Pulse.Syntax.Base.comp_pre" ]
[]
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 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 let opened = elab_term (comp_inames c) in if C_STAtomic? c then mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else let _ = assert (C_STGhost? c) in mk_frame_stt_ghost u ty opened 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 let opened = elab_term (comp_inames c1) in if C_STAtomic? c1 then mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else let _ = assert (C_STGhost? c1) in mk_sub_stt_ghost u ty opened 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 bc with | Bind_comp _ _ _ _ _ _ _ -> if C_ST? c1 then 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 else mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 | Bind_comp_ghost_l _ _ _ _ (| reveal_a, reveal_a_typing |) _ _ _ -> mk_bind_ghost_atomic (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_a) | Bind_comp_ghost_r _ _ _ _ (| reveal_b, reveal_b_typing |) _ _ _ -> mk_bind_atomic_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_b) let elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term)
false
false
Pulse.Elaborate.Core.fst
{ "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" }
null
val elab_lift (#g #c1 #c2: _) (d: lift_comp g c1 c2) (e: R.term) : Tot R.term
[]
Pulse.Elaborate.Core.elab_lift
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
d: Pulse.Typing.lift_comp g c1 c2 -> e: FStar.Reflection.Types.term -> FStar.Reflection.Types.term
{ "end_col": 28, "end_line": 116, "start_col": 4, "start_line": 97 }
Prims.Tot
val elab_bind (#g #x #c1 #c2 #c: _) (bc: bind_comp g x c1 c2 c) (e1 e2: R.term) : R.term
[ { "abbrev": false, "full_module": "Pulse.Reflection.Util", "short_module": null }, { "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 } ]
false
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 bc with | Bind_comp _ _ _ _ _ _ _ -> if C_ST? c1 then 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 else mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 | Bind_comp_ghost_l _ _ _ _ (| reveal_a, reveal_a_typing |) _ _ _ -> mk_bind_ghost_atomic (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_a) | Bind_comp_ghost_r _ _ _ _ (| reveal_b, reveal_b_typing |) _ _ _ -> mk_bind_atomic_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_b)
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: R.term) (e2: R.term) : R.term =
false
null
false
let t1 = elab_term (comp_res c1) in let t2 = elab_term (comp_res c2) in match bc with | Bind_comp _ _ _ _ _ _ _ -> if C_ST? c1 then 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 else mk_bind_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 | Bind_comp_ghost_l _ _ _ _ (| reveal_a , reveal_a_typing |) _ _ _ -> mk_bind_ghost_atomic (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_a) | Bind_comp_ghost_r _ _ _ _ (| reveal_b , reveal_b_typing |) _ _ _ -> mk_bind_atomic_ghost (comp_u c1) (comp_u c2) t1 t2 (elab_term (comp_inames c1)) (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 (elab_term reveal_b)
{ "checked_file": "Pulse.Elaborate.Core.fst.checked", "dependencies": [ "Pulse.Typing.fst.checked", "Pulse.Syntax.fst.checked", "Pulse.Reflection.Util.fst.checked", "Pulse.Elaborate.Pure.fst.checked", "prims.fst.checked", "FStar.Tactics.V2.fst.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" }
[ "total" ]
[ "Pulse.Typing.Env.env", "Pulse.Syntax.Base.var", "Pulse.Syntax.Base.comp", "Pulse.Typing.bind_comp", "FStar.Reflection.Types.term", "Prims.b2t", "FStar.Pervasives.Native.uu___is_None", "Pulse.Syntax.Base.typ", "Pulse.Typing.Env.lookup", "Pulse.Syntax.Base.comp_st", "Pulse.Typing.bind_comp_pre", "Pulse.Typing.universe_of", "Pulse.Syntax.Base.comp_res", "Pulse.Syntax.Base.comp_u", "Prims.l_and", "Prims.l_not", "FStar.Set.mem", "Pulse.Syntax.Naming.freevars", "Pulse.Syntax.Base.comp_post", "Pulse.Typing.tot_typing", "Pulse.Typing.Env.push_binding", "Pulse.Syntax.Base.ppname_default", "Pulse.Syntax.Naming.open_term", "Pulse.Syntax.Base.tm_vprop", "Pulse.Syntax.Base.uu___is_C_ST", "Pulse.Reflection.Util.mk_bind_stt", "Pulse.Elaborate.Pure.elab_term", "Pulse.Syntax.Base.comp_pre", "Pulse.Reflection.Util.mk_abs", "FStar.Reflection.V2.Data.Q_Explicit", "Prims.bool", "Pulse.Reflection.Util.mk_bind_ghost", "Pulse.Syntax.Base.comp_inames", "Pulse.Typing.bind_comp_ghost_l_pre", "Pulse.Syntax.Base.term", "Pulse.Typing.non_informative_witness_t", "Pulse.Reflection.Util.mk_bind_ghost_atomic", "Pulse.Typing.bind_comp_ghost_r_pre", "Pulse.Reflection.Util.mk_bind_atomic_ghost" ]
[]
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 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 let opened = elab_term (comp_inames c) in if C_STAtomic? c then mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e else let _ = assert (C_STGhost? c) in mk_frame_stt_ghost u ty opened 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 let opened = elab_term (comp_inames c1) in if C_STAtomic? c1 then mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e else let _ = assert (C_STGhost? c1) in mk_sub_stt_ghost u ty opened 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)
false
false
Pulse.Elaborate.Core.fst
{ "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" }
null
val elab_bind (#g #x #c1 #c2 #c: _) (bc: bind_comp g x c1 c2 c) (e1 e2: R.term) : R.term
[]
Pulse.Elaborate.Core.elab_bind
{ "file_name": "lib/steel/pulse/Pulse.Elaborate.Core.fst", "git_rev": "7fbb54e94dd4f48ff7cb867d3bae6889a635541e", "git_url": "https://github.com/FStarLang/steel.git", "project_name": "steel" }
bc: Pulse.Typing.bind_comp g x c1 c2 c -> e1: FStar.Reflection.Types.term -> e2: FStar.Reflection.Types.term -> FStar.Reflection.Types.term
{ "end_col": 28, "end_line": 93, "start_col": 3, "start_line": 46 }
Prims.Tot
[ { "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 } ]
false
let u1024 = b:B.buffer UInt64.t{B.length b == 16}
let u1024 =
false
null
false
b: B.buffer UInt64.t {B.length b == 16}
{ "checked_file": "Vale.Inline.X64.Fadd_inline.fsti.checked", "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" }
[ "total" ]
[ "LowStar.Buffer.buffer", "FStar.UInt64.t", "Prims.eq2", "Prims.int", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder" ]
[]
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}
false
true
Vale.Inline.X64.Fadd_inline.fsti
{ "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" }
null
val u1024 : Type0
[]
Vale.Inline.X64.Fadd_inline.u1024
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
Type0
{ "end_col": 49, "end_line": 15, "start_col": 12, "start_line": 15 }
Prims.Tot
[ { "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 } ]
false
let u256 = b:B.buffer UInt64.t{B.length b == 4}
let u256 =
false
null
false
b: B.buffer UInt64.t {B.length b == 4}
{ "checked_file": "Vale.Inline.X64.Fadd_inline.fsti.checked", "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" }
[ "total" ]
[ "LowStar.Buffer.buffer", "FStar.UInt64.t", "Prims.eq2", "Prims.int", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder" ]
[]
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
false
true
Vale.Inline.X64.Fadd_inline.fsti
{ "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" }
null
val u256 : Type0
[]
Vale.Inline.X64.Fadd_inline.u256
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
Type0
{ "end_col": 47, "end_line": 11, "start_col": 11, "start_line": 11 }
Prims.Tot
[ { "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 } ]
false
let u512 = b:B.buffer UInt64.t{B.length b == 8}
let u512 =
false
null
false
b: B.buffer UInt64.t {B.length b == 8}
{ "checked_file": "Vale.Inline.X64.Fadd_inline.fsti.checked", "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" }
[ "total" ]
[ "LowStar.Buffer.buffer", "FStar.UInt64.t", "Prims.eq2", "Prims.int", "LowStar.Monotonic.Buffer.length", "LowStar.Buffer.trivial_preorder" ]
[]
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}
false
true
Vale.Inline.X64.Fadd_inline.fsti
{ "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" }
null
val u512 : Type0
[]
Vale.Inline.X64.Fadd_inline.u512
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
Type0
{ "end_col": 47, "end_line": 13, "start_col": 11, "start_line": 13 }
Prims.GTot
val as_nat (b: B.buffer UInt64.t {B.length b == 4}) (h: HS.mem) : GTot nat
[ { "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 } ]
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
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 =
false
null
false
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
{ "checked_file": "Vale.Inline.X64.Fadd_inline.fsti.checked", "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" }
[ "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" ]
[]
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}
false
false
Vale.Inline.X64.Fadd_inline.fsti
{ "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" }
null
val as_nat (b: B.buffer UInt64.t {B.length b == 4}) (h: HS.mem) : GTot nat
[]
Vale.Inline.X64.Fadd_inline.as_nat
{ "file_name": "vale/code/arch/x64/interop/Vale.Inline.X64.Fadd_inline.fsti", "git_rev": "12c5e9539c7e3c366c26409d3b86493548c4483e", "git_url": "https://github.com/hacl-star/hacl-star.git", "project_name": "hacl-star" }
b: LowStar.Buffer.buffer FStar.UInt64.t {LowStar.Monotonic.Buffer.length b == 4} -> h: FStar.Monotonic.HyperStack.mem -> Prims.GTot Prims.nat
{ "end_col": 23, "end_line": 23, "start_col": 73, "start_line": 17 }
Prims.Tot
[ { "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 } ]
false
let absvar = binding
let absvar =
false
null
false
binding
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.NamedView.binding" ]
[]
(* 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 /// -----------
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val absvar : Type0
[]
FStar.Tactics.PatternMatching.absvar
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
Type0
{ "end_col": 20, "end_line": 349, "start_col": 13, "start_line": 349 }
Prims.Tot
[ { "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 } ]
false
let hyp_qn = `%hyp
let hyp_qn =
false
null
false
`%hyp
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[]
[]
(* 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
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val hyp_qn : Prims.string
[]
FStar.Tactics.PatternMatching.hyp_qn
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
Prims.string
{ "end_col": 19, "end_line": 562, "start_col": 16, "start_line": 562 }
FStar.Tactics.Effect.Tac
val interp_pattern: pat: pattern -> term -> Tac (match_res bindings)
[ { "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 } ]
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)
val interp_pattern: pat: pattern -> term -> Tac (match_res bindings) let interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =
true
null
false
fun (tm: term) -> let? rev_bindings = interp_pattern_aux pat [] tm in return (List.Tot.Base.rev rev_bindings)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val interp_pattern: pat: pattern -> term -> Tac (match_res bindings)
[]
FStar.Tactics.PatternMatching.interp_pattern
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
pat: FStar.Tactics.PatternMatching.pattern -> _: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.match_res FStar.Tactics.PatternMatching.bindings)
{ "end_col": 43, "end_line": 328, "start_col": 2, "start_line": 326 }
FStar.Tactics.Effect.Tac
val exact_hyp (a: Type0) (h: namedv) : Tac unit
[ { "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 } ]
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)])
val exact_hyp (a: Type0) (h: namedv) : Tac unit let exact_hyp (a: Type0) (h: namedv) : Tac unit =
true
null
false
let hd = quote (FStar.Squash.return_squash #a) in exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.namedv", "FStar.Tactics.V2.Derived.exact", "FStar.Reflection.V2.Derived.mk_app", "Prims.Cons", "FStar.Reflection.V2.Data.argv", "FStar.Pervasives.Native.Mktuple2", "FStar.Reflection.Types.term", "FStar.Reflection.V2.Data.aqualv", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Var", "FStar.Reflection.V2.Data.Q_Explicit", "Prims.Nil", "Prims.unit", "FStar.Squash.return_squash" ]
[]
(* 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
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val exact_hyp (a: Type0) (h: namedv) : Tac unit
[]
FStar.Tactics.PatternMatching.exact_hyp
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
a: Type0 -> h: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.unit
{ "end_col": 53, "end_line": 150, "start_col": 49, "start_line": 148 }
FStar.Tactics.Effect.Tac
val repeat' (#a: _) (f: (unit -> Tac a)) : Tac unit
[ { "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 } ]
false
let repeat' #a (f: unit -> Tac a) : Tac unit = let _ = repeat f in ()
val repeat' (#a: _) (f: (unit -> Tac a)) : Tac unit let repeat' #a (f: (unit -> Tac a)) : Tac unit =
true
null
false
let _ = repeat f in ()
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "Prims.unit", "Prims.list", "FStar.Tactics.V2.Derived.repeat" ]
[]
(* 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 ()
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val repeat' (#a: _) (f: (unit -> Tac a)) : Tac unit
[]
FStar.Tactics.PatternMatching.repeat'
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
f: (_: Prims.unit -> FStar.Tactics.Effect.Tac a) -> FStar.Tactics.Effect.Tac Prims.unit
{ "end_col": 24, "end_line": 141, "start_col": 46, "start_line": 140 }
FStar.Tactics.Effect.Tac
val implies_intro': Prims.unit -> Tac unit
[ { "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 } ]
false
let implies_intro' () : Tac unit = let _ = implies_intro () in ()
val implies_intro': Prims.unit -> Tac unit let implies_intro' () : Tac unit =
true
null
false
let _ = implies_intro () in ()
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "Prims.unit", "FStar.Tactics.NamedView.binding", "FStar.Tactics.V2.Logic.implies_intro" ]
[]
(* 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.
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val implies_intro': Prims.unit -> Tac unit
[]
FStar.Tactics.PatternMatching.implies_intro'
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
_: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit
{ "end_col": 32, "end_line": 138, "start_col": 34, "start_line": 137 }
FStar.Tactics.Effect.Tac
val and_elim' (h: binding) : Tac unit
[ { "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 } ]
false
let and_elim' (h: binding) : Tac unit = and_elim (pack (Tv_Var h)); clear h
val and_elim' (h: binding) : Tac unit let and_elim' (h: binding) : Tac unit =
true
null
false
and_elim (pack (Tv_Var h)); clear h
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.binding", "FStar.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" ]
[]
(* 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 ()
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val and_elim' (h: binding) : Tac unit
[]
FStar.Tactics.PatternMatching.and_elim'
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
h: FStar.Tactics.NamedView.binding -> FStar.Tactics.Effect.Tac Prims.unit
{ "end_col": 9, "end_line": 145, "start_col": 2, "start_line": 144 }
Prims.Tot
val raise (#a: _) (ex: match_exception) : match_res a
[ { "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 } ]
false
let raise #a (ex: match_exception) : match_res a = Failure ex
val raise (#a: _) (ex: match_exception) : match_res a let raise #a (ex: match_exception) : match_res a =
false
null
false
Failure ex
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.PatternMatching.Failure", "FStar.Tactics.PatternMatching.match_res" ]
[]
(* 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
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val raise (#a: _) (ex: match_exception) : match_res a
[]
FStar.Tactics.PatternMatching.raise
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
ex: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.PatternMatching.match_res a
{ "end_col": 12, "end_line": 259, "start_col": 2, "start_line": 259 }
FStar.Tactics.Effect.Tac
val exact_hyp' (h: namedv) : Tac unit
[ { "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 } ]
false
let exact_hyp' (h: namedv): Tac unit = exact (pack (Tv_Var h))
val exact_hyp' (h: namedv) : Tac unit let exact_hyp' (h: namedv) : Tac unit =
true
null
false
exact (pack (Tv_Var h))
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.namedv", "FStar.Tactics.V2.Derived.exact", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.Tv_Var", "Prims.unit" ]
[]
(* 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 *)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val exact_hyp' (h: namedv) : Tac unit
[]
FStar.Tactics.PatternMatching.exact_hyp'
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
h: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.unit
{ "end_col": 25, "end_line": 154, "start_col": 2, "start_line": 154 }
FStar.Tactics.Effect.Tac
[ { "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 } ]
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 ^ " }"
let string_of_matching_solution ms =
true
null
false
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": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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.Reflection.Types.term", "FStar.Tactics.V2.Builtins.term_to_string", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_vars" ]
[]
(* 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) }
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val string_of_matching_solution : ms: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac Prims.string
[]
FStar.Tactics.PatternMatching.string_of_matching_solution
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
ms: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac Prims.string
{ "end_col": 26, "end_line": 391, "start_col": 36, "start_line": 381 }
Prims.Tot
[ { "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 } ]
false
let goal_qn = `%pm_goal
let goal_qn =
false
null
false
`%pm_goal
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[]
[]
(* 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
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val goal_qn : Prims.string
[]
FStar.Tactics.PatternMatching.goal_qn
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
Prims.string
{ "end_col": 23, "end_line": 563, "start_col": 16, "start_line": 563 }
FStar.Tactics.Effect.Tac
[ { "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 } ]
false
let string_of_bindings (bindings: bindings) = String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings)
let string_of_bindings (bindings: bindings) =
true
null
false
String.concat "\n" (map (fun (nm, tm) -> (">> " ^ nm ^ ": " ^ term_to_string tm)) bindings)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.bindings", "FStar.String.concat", "Prims.string", "Prims.list", "FStar.Tactics.Util.map", "FStar.Pervasives.Native.tuple2", "FStar.Reflection.Types.term", "Prims.op_Hat", "FStar.Tactics.V2.Builtins.term_to_string" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val string_of_bindings : bindings: FStar.Tactics.PatternMatching.bindings -> FStar.Tactics.Effect.Tac Prims.string
[]
FStar.Tactics.PatternMatching.string_of_bindings
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
bindings: FStar.Tactics.PatternMatching.bindings -> FStar.Tactics.Effect.Tac Prims.string
{ "end_col": 27, "end_line": 287, "start_col": 2, "start_line": 285 }
FStar.Tactics.Effect.Tac
val beta_reduce (tm: term) : Tac term
[ { "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 } ]
false
let beta_reduce (tm: term) : Tac term = norm_term [] tm
val beta_reduce (tm: term) : Tac term let beta_reduce (tm: term) : Tac term =
true
null
false
norm_term [] tm
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.term", "FStar.Tactics.V2.Derived.norm_term", "Prims.Nil", "FStar.Pervasives.norm_step" ]
[]
(* 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``. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val beta_reduce (tm: term) : Tac term
[]
FStar.Tactics.PatternMatching.beta_reduce
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
tm: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
{ "end_col": 17, "end_line": 527, "start_col": 2, "start_line": 527 }
Prims.Tot
val return (#a: _) (x: a) : match_res a
[ { "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 } ]
false
let return #a (x: a) : match_res a = Success x
val return (#a: _) (x: a) : match_res a let return #a (x: a) : match_res a =
false
null
false
Success x
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.PatternMatching.Success", "FStar.Tactics.PatternMatching.match_res" ]
[]
(* 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
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val return (#a: _) (x: a) : match_res a
[]
FStar.Tactics.PatternMatching.return
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
x: a -> FStar.Tactics.PatternMatching.match_res a
{ "end_col": 11, "end_line": 248, "start_col": 2, "start_line": 248 }
Prims.Tot
val type_of_named_binder (nb: binder) : term
[ { "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 } ]
false
let type_of_named_binder (nb : binder) : term = nb.sort
val type_of_named_binder (nb: binder) : term let type_of_named_binder (nb: binder) : term =
false
null
false
nb.sort
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.NamedView.binder", "FStar.Tactics.NamedView.__proj__Mkbinder__item__sort", "FStar.Tactics.NamedView.term" ]
[]
(* 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
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val type_of_named_binder (nb: binder) : term
[]
FStar.Tactics.PatternMatching.type_of_named_binder
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
nb: FStar.Tactics.NamedView.binder -> FStar.Tactics.NamedView.term
{ "end_col": 8, "end_line": 585, "start_col": 1, "start_line": 585 }
FStar.Tactics.Effect.Tac
val name_of_namedv (x: namedv) : Tac string
[ { "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 } ]
false
let name_of_namedv (x:namedv) : Tac string = unseal (inspect_namedv x).ppname
val name_of_namedv (x: namedv) : Tac string let name_of_namedv (x: namedv) : Tac string =
true
null
false
unseal (inspect_namedv x).ppname
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.namedv", "FStar.Tactics.Unseal.unseal", "Prims.string", "FStar.Reflection.V2.Data.__proj__Mknamedv_view__item__ppname", "FStar.Tactics.NamedView.inspect_namedv" ]
[]
(* 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 *)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val name_of_namedv (x: namedv) : Tac string
[]
FStar.Tactics.PatternMatching.name_of_namedv
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
x: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.string
{ "end_col": 34, "end_line": 504, "start_col": 2, "start_line": 504 }
FStar.Tactics.Effect.Tac
val inspect_abspat_problem (#a: _) (abspat: a) : Tac matching_problem
[ { "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 } ]
false
let inspect_abspat_problem #a (abspat: a) : Tac matching_problem = fst (interp_abspat #a abspat)
val inspect_abspat_problem (#a: _) (abspat: a) : Tac matching_problem let inspect_abspat_problem #a (abspat: a) : Tac matching_problem =
true
null
false
fst (interp_abspat #a abspat)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Pervasives.Native.fst", "FStar.Tactics.PatternMatching.matching_problem", "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.interp_abspat" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val inspect_abspat_problem (#a: _) (abspat: a) : Tac matching_problem
[]
FStar.Tactics.PatternMatching.inspect_abspat_problem
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
abspat: a -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.matching_problem
{ "end_col": 31, "end_line": 780, "start_col": 2, "start_line": 780 }
FStar.Tactics.Effect.Tac
val cleanup_abspat (t: term) : Tac term
[ { "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 } ]
false
let cleanup_abspat (t: term) : Tac term = norm_term [] t
val cleanup_abspat (t: term) : Tac term let cleanup_abspat (t: term) : Tac term =
true
null
false
norm_term [] t
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.term", "FStar.Tactics.V2.Derived.norm_term", "Prims.Nil", "FStar.Pervasives.norm_step" ]
[]
(* 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
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val cleanup_abspat (t: term) : Tac term
[]
FStar.Tactics.PatternMatching.cleanup_abspat
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
{ "end_col": 16, "end_line": 611, "start_col": 2, "start_line": 611 }
FStar.Tactics.Effect.Tac
val name_of_named_binder (nb: binder) : Tac string
[ { "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 } ]
false
let name_of_named_binder (nb : binder) : Tac string = unseal nb.ppname
val name_of_named_binder (nb: binder) : Tac string let name_of_named_binder (nb: binder) : Tac string =
true
null
false
unseal nb.ppname
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.binder", "FStar.Tactics.Unseal.unseal", "Prims.string", "FStar.Tactics.NamedView.__proj__Mkbinder__item__ppname" ]
[]
(* 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
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val name_of_named_binder (nb: binder) : Tac string
[]
FStar.Tactics.PatternMatching.name_of_named_binder
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
nb: FStar.Tactics.NamedView.binder -> FStar.Tactics.Effect.Tac Prims.string
{ "end_col": 17, "end_line": 615, "start_col": 1, "start_line": 615 }
FStar.Tactics.Effect.Tac
val inspect_abspat_solution (#a: _) (abspat: a) : Tac matching_solution
[ { "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 } ]
false
let inspect_abspat_solution #a (abspat: a) : Tac matching_solution = match_abspat abspat (fun _ -> (fun solution -> solution <: Tac _) <: Tac _)
val inspect_abspat_solution (#a: _) (abspat: a) : Tac matching_solution let inspect_abspat_solution #a (abspat: a) : Tac matching_solution =
true
null
false
match_abspat abspat (fun _ -> (fun solution -> solution <: Tac _) <: Tac _)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.match_abspat", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.abspat_continuation" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val inspect_abspat_solution (#a: _) (abspat: a) : Tac matching_solution
[]
FStar.Tactics.PatternMatching.inspect_abspat_solution
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
abspat: a -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.matching_solution
{ "end_col": 77, "end_line": 784, "start_col": 2, "start_line": 784 }
FStar.Tactics.Effect.Tac
val interp_abspat_continuation (a: Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a)
[ { "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 } ]
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
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) =
true
null
false
let applied = specialize_abspat_continuation continuation in unquote #(matching_solution -> Tac a) applied
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Tactics.V2.Builtins.unquote", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.specialize_abspat_continuation" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val interp_abspat_continuation (a: Type0) (continuation: abspat_continuation) : Tac (matching_solution -> Tac a)
[]
FStar.Tactics.PatternMatching.interp_abspat_continuation
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
a: Type0 -> continuation: FStar.Tactics.PatternMatching.abspat_continuation -> FStar.Tactics.Effect.Tac (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a)
{ "end_col": 47, "end_line": 755, "start_col": 40, "start_line": 753 }
FStar.Tactics.Effect.Tac
val specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term) : Tac term
[ { "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 } ]
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) []
val specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term) : Tac term let specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term) : Tac term =
true
null
false
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) []
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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.Reflection.V2.Data.argv", "FStar.Tactics.Util.map", "FStar.Tactics.PatternMatching.abspat_arg_of_abspat_argspec" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term) : Tac term
[]
FStar.Tactics.PatternMatching.specialize_abspat_continuation'
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
continuation: FStar.Tactics.PatternMatching.abspat_continuation -> solution_term: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
{ "end_col": 52, "end_line": 733, "start_col": 16, "start_line": 729 }
FStar.Tactics.Effect.Tac
val match_abspat (#b #a: _) (abspat: a) (k: (abspat_continuation -> Tac (matching_solution -> Tac b))) : Tac b
[ { "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 } ]
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)
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 =
true
null
false
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": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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.Reflection.V2.Data.binding", "FStar.Reflection.V2.Builtins.vars_of_env", "FStar.Reflection.Types.env", "FStar.Tactics.V2.Derived.cur_env", "FStar.Reflection.Types.typ", "FStar.Tactics.V2.Derived.cur_goal" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val match_abspat (#b #a: _) (abspat: a) (k: (abspat_continuation -> Tac (matching_solution -> Tac b))) : Tac b
[]
FStar.Tactics.PatternMatching.match_abspat
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
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
{ "end_col": 51, "end_line": 776, "start_col": 13, "start_line": 772 }
FStar.Tactics.Effect.Tac
val tpair (#a #b: _) (x: a) : Tac (b -> Tac (a * b))
[ { "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 } ]
false
let tpair #a #b (x : a) : Tac (b -> Tac (a * b)) = fun (y: b) -> (x, y)
val tpair (#a #b: _) (x: a) : Tac (b -> Tac (a * b)) let tpair #a #b (x: a) : Tac (b -> Tac (a * b)) =
true
null
false
fun (y: b) -> (x, y)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Pervasives.Native.Mktuple2", "FStar.Pervasives.Native.tuple2" ]
[]
(* 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 _)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val tpair (#a #b: _) (x: a) : Tac (b -> Tac (a * b))
[]
FStar.Tactics.PatternMatching.tpair
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
x: a -> FStar.Tactics.Effect.Tac (_: b -> FStar.Tactics.Effect.Tac (a * b))
{ "end_col": 22, "end_line": 787, "start_col": 2, "start_line": 787 }
FStar.Tactics.Effect.Tac
val ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis
[ { "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 } ]
false
let ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis = assoc_varname_fail name solution.ms_hyps
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 =
true
null
false
assoc_varname_fail name solution.ms_hyps
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis
[]
FStar.Tactics.PatternMatching.ms_locate_hyp
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
a: Type -> solution: FStar.Tactics.PatternMatching.matching_solution -> name: FStar.Tactics.PatternMatching.varname -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.hypothesis
{ "end_col": 42, "end_line": 402, "start_col": 2, "start_line": 402 }
FStar.Tactics.Effect.Tac
val ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a
[ { "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 } ]
false
let ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a = unquote #a (assoc_varname_fail name solution.ms_vars)
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 =
true
null
false
unquote #a (assoc_varname_fail name solution.ms_vars)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.V2.Builtins.unquote", "FStar.Reflection.Types.term", "FStar.Tactics.PatternMatching.assoc_varname_fail", "FStar.Tactics.NamedView.term", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_vars" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a
[]
FStar.Tactics.PatternMatching.ms_locate_var
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
a: Type -> solution: FStar.Tactics.PatternMatching.matching_solution -> name: FStar.Tactics.PatternMatching.varname -> FStar.Tactics.Effect.Tac a
{ "end_col": 55, "end_line": 406, "start_col": 2, "start_line": 406 }
Prims.Tot
[ { "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 } ]
false
let hyp (a: Type) = binding
let hyp (a: Type) =
false
null
false
binding
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.NamedView.binding" ]
[]
(* 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.
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val hyp : a: Type -> Type0
[]
FStar.Tactics.PatternMatching.hyp
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
a: Type -> Type0
{ "end_col": 27, "end_line": 559, "start_col": 20, "start_line": 559 }
FStar.Tactics.Effect.Tac
val specialize_abspat_continuation (continuation: abspat_continuation) : Tac term
[ { "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 } ]
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 ("… which reduces to " ^ (term_to_string normalized)); thunked
val specialize_abspat_continuation (continuation: abspat_continuation) : Tac term let specialize_abspat_continuation (continuation: abspat_continuation) : Tac term =
true
null
false
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
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Tactics.NamedView.term", "Prims.unit", "FStar.Tactics.PatternMatching.debug", "Prims.string", "Prims.op_Hat", "FStar.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" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val specialize_abspat_continuation (continuation: abspat_continuation) : Tac term
[]
FStar.Tactics.PatternMatching.specialize_abspat_continuation
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
continuation: FStar.Tactics.PatternMatching.abspat_continuation -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
{ "end_col": 9, "end_line": 747, "start_col": 16, "start_line": 739 }
FStar.Tactics.Effect.Tac
val interp_abspat (#a: _) (abspat: a) : Tac (matching_problem * abspat_continuation)
[ { "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 } ]
false
let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) = matching_problem_of_abs (quote abspat)
val interp_abspat (#a: _) (abspat: a) : Tac (matching_problem * abspat_continuation) let interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) =
true
null
false
matching_problem_of_abs (quote abspat)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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.Reflection.Types.term" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val interp_abspat (#a: _) (abspat: a) : Tac (matching_problem * abspat_continuation)
[]
FStar.Tactics.PatternMatching.interp_abspat
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
abspat: a -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.matching_problem * FStar.Tactics.PatternMatching.abspat_continuation)
{ "end_col": 40, "end_line": 765, "start_col": 2, "start_line": 765 }
FStar.Tactics.Effect.Tac
val fetch_eq_side: Prims.unit -> Tac (term * term)
[ { "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 } ]
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"
val fetch_eq_side: Prims.unit -> Tac (term * term) let fetch_eq_side () : Tac (term * term) =
true
null
false
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"
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "Prims.unit", "FStar.Tactics.NamedView.term", "FStar.Reflection.Types.term", "FStar.Reflection.V2.Data.aqualv", "FStar.Reflection.Types.fv", "FStar.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.Reflection.Types.typ", "FStar.Tactics.V2.Derived.cur_goal" ]
[]
(* 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:
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val fetch_eq_side: Prims.unit -> Tac (term * term)
[]
FStar.Tactics.PatternMatching.fetch_eq_side
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
_: Prims.unit -> FStar.Tactics.Effect.Tac (FStar.Tactics.NamedView.term * FStar.Tactics.NamedView.term)
{ "end_col": 39, "end_line": 88, "start_col": 42, "start_line": 62 }
Prims.Tot
[ { "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 } ]
false
let desc_of_pattern = function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application"
let desc_of_pattern =
false
null
false
function | PVar _ -> "a variable" | PQn qn -> "a constant (" ^ qn ^ ")" | PType -> "Type" | PApp _ _ -> "a function application"
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.qn", "Prims.op_Hat", "Prims.string" ]
[]
(* 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
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val desc_of_pattern : _: FStar.Tactics.PatternMatching.pattern -> Prims.string
[]
FStar.Tactics.PatternMatching.desc_of_pattern
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
_: FStar.Tactics.PatternMatching.pattern -> Prims.string
{ "end_col": 38, "end_line": 176, "start_col": 22, "start_line": 172 }
FStar.Tactics.Effect.Tac
val lift_exn_tactic (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
[ { "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 } ]
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)
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 =
true
null
false
match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.V1.Derived.fail", "Prims.string", "FStar.Tactics.PatternMatching.string_of_match_exception" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val lift_exn_tactic (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
[]
FStar.Tactics.PatternMatching.lift_exn_tactic
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
f: (_: a -> FStar.Tactics.PatternMatching.match_res b) -> aa: a -> FStar.Tactics.Effect.Tac b
{ "end_col": 61, "end_line": 274, "start_col": 2, "start_line": 272 }
FStar.Tactics.Effect.Tac
val op_let_Question (#a #b: Type) (f: match_res a) (g: (a -> Tac (match_res b))) : Tac (match_res b)
[ { "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 } ]
false
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
val op_let_Question (#a #b: Type) (f: match_res a) (g: (a -> Tac (match_res b))) : Tac (match_res b) let op_let_Question (#a #b: Type) (f: match_res a) (g: (a -> Tac (match_res b))) : Tac (match_res b) =
true
null
false
match f with | Success aa -> g aa | Failure ex -> Failure ex
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.PatternMatching.Failure" ]
[]
(* 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))
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val op_let_Question (#a #b: Type) (f: match_res a) (g: (a -> Tac (match_res b))) : Tac (match_res b)
[]
FStar.Tactics.PatternMatching.op_let_Question
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
f: FStar.Tactics.PatternMatching.match_res a -> g: (_: a -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.match_res b)) -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.match_res b)
{ "end_col": 28, "end_line": 256, "start_col": 2, "start_line": 254 }
Prims.Tot
[ { "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 } ]
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 ^ " }"
let string_of_matching_problem mp =
false
null
false
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 ^ " }"
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "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" ]
[]
(* 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 }
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val string_of_matching_problem : mp: FStar.Tactics.PatternMatching.matching_problem -> Prims.string
[]
FStar.Tactics.PatternMatching.string_of_matching_problem
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
mp: FStar.Tactics.PatternMatching.matching_problem -> Prims.string
{ "end_col": 26, "end_line": 372, "start_col": 35, "start_line": 360 }
FStar.Tactics.Effect.Tac
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
[ { "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 } ]
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
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 =
true
null
false
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
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
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
[ "recursion" ]
FStar.Tactics.PatternMatching.solve_mp_for_hyps
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
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
{ "end_col": 22, "end_line": 468, "start_col": 2, "start_line": 463 }
FStar.Tactics.Effect.Tac
val assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b
[ { "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 } ]
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
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 =
true
null
false
match List.Tot.Base.assoc key ls with | None -> fail ("Not found: " ^ key) | Some x -> x
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.varname", "Prims.list", "FStar.Pervasives.Native.tuple2", "FStar.List.Tot.Base.assoc", "FStar.Tactics.V2.Derived.fail", "Prims.op_Hat" ]
[]
(* 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))
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b
[]
FStar.Tactics.PatternMatching.assoc_varname_fail
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
key: FStar.Tactics.PatternMatching.varname -> ls: Prims.list (FStar.Tactics.PatternMatching.varname * b) -> FStar.Tactics.Effect.Tac b
{ "end_col": 15, "end_line": 398, "start_col": 2, "start_line": 396 }
FStar.Tactics.Effect.Tac
val hoist_and_apply (head: term) (arg_terms: list term) (hoisted_args: list argv) : Tac term
[ { "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 } ]
false
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)))
val hoist_and_apply (head: term) (arg_terms: list term) (hoisted_args: list argv) : Tac term let rec hoist_and_apply (head: term) (arg_terms: list term) (hoisted_args: list argv) : Tac term =
true
null
false
match arg_terms with | [] -> mk_app head (List.rev hoisted_args) | arg_term :: rest -> let n = List.Tot.length hoisted_args 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": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Reflection.V2.Data.argv", "FStar.Reflection.V2.Derived.mk_app", "FStar.List.Tot.Base.rev", "FStar.Tactics.NamedView.pack", "FStar.Tactics.NamedView.named_term_view", "FStar.Tactics.NamedView.Tv_Let", "Prims.Nil", "FStar.Tactics.PatternMatching.hoist_and_apply", "Prims.Cons", "FStar.Pervasives.Native.Mktuple2", "FStar.Reflection.Types.term", "FStar.Reflection.V2.Data.aqualv", "FStar.Tactics.NamedView.Tv_Var", "FStar.Tactics.V2.SyntaxCoercions.binder_to_namedv", "FStar.Reflection.V2.Data.Q_Explicit", "FStar.Tactics.NamedView.binder", "FStar.Tactics.NamedView.Mkbinder", "FStar.Sealed.seal", "Prims.string", "Prims.op_Hat", "Prims.string_of_int", "FStar.Tactics.NamedView.Tv_Unknown", "Prims.nat", "FStar.Tactics.V2.Builtins.fresh", "FStar.List.Tot.Base.length" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val hoist_and_apply (head: term) (arg_terms: list term) (hoisted_args: list argv) : Tac term
[ "recursion" ]
FStar.Tactics.PatternMatching.hoist_and_apply
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
head: FStar.Tactics.NamedView.term -> arg_terms: Prims.list FStar.Tactics.NamedView.term -> hoisted_args: Prims.list FStar.Reflection.V2.Data.argv -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term
{ "end_col": 132, "end_line": 725, "start_col": 2, "start_line": 712 }
FStar.Tactics.Effect.Tac
val lift_exn_tac (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
[ { "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 } ]
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)
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 =
true
null
false
match f aa with | Success bb -> bb | Failure ex -> Tactics.fail (string_of_match_exception ex)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.V1.Derived.fail", "Prims.string", "FStar.Tactics.PatternMatching.string_of_match_exception" ]
[]
(* 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:
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val lift_exn_tac (#a #b: _) (f: (a -> match_res b)) (aa: a) : Tac b
[]
FStar.Tactics.PatternMatching.lift_exn_tac
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
f: (_: a -> FStar.Tactics.PatternMatching.match_res b) -> aa: a -> FStar.Tactics.Effect.Tac b
{ "end_col": 61, "end_line": 269, "start_col": 2, "start_line": 267 }
FStar.Tactics.Effect.Tac
[ { "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 } ]
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 …``, or ``goal …``)"
let string_of_match_exception =
true
null
false
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``)"
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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.Tactics.V2.Builtins.term_to_string", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.term_head", "FStar.Reflection.Types.typ" ]
[]
(* 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"
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val string_of_match_exception : _: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.Effect.Tac Prims.string
[]
FStar.Tactics.PatternMatching.string_of_match_exception
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
_: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.Effect.Tac Prims.string
{ "end_col": 74, "end_line": 238, "start_col": 32, "start_line": 222 }
FStar.Tactics.Effect.Tac
val interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm: term) : Tac (match_res bindings)
[ { "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 } ]
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_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
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) =
true
null
false
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
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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.Reflection.Types.term", "FStar.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.Reflection.Types.fv", "FStar.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.Reflection.V2.Builtins.term_eq", "FStar.Tactics.PatternMatching.NonLinearMismatch", "FStar.Pervasives.Native.Mktuple3", "Prims.Cons" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm: term) : Tac (match_res bindings)
[ "recursion" ]
FStar.Tactics.PatternMatching.interp_pattern_aux
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
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)
{ "end_col": 62, "end_line": 321, "start_col": 32, "start_line": 293 }
FStar.Tactics.Effect.Tac
val matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation)
[ { "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 } ]
false
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
val matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) let matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation) =
true
null
false
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
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.term", "Prims.list", "FStar.Tactics.NamedView.binder", "FStar.Pervasives.Native.Mktuple2", "FStar.Tactics.PatternMatching.matching_problem", "FStar.Tactics.PatternMatching.abspat_continuation", "FStar.Pervasives.Native.tuple2", "Prims.unit", "FStar.Tactics.PatternMatching.debug", "Prims.string", "Prims.op_Hat", "FStar.Tactics.PatternMatching.string_of_matching_problem", "FStar.Tactics.PatternMatching.Mkmatching_problem", "FStar.List.Tot.Base.rev", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_vars", "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_hyps", "FStar.Tactics.PatternMatching.__proj__Mkmatching_problem__item__mp_goal", "FStar.Tactics.PatternMatching.abspat_argspec", "FStar.Tactics.Util.map", "FStar.Pervasives.Native.tuple4", "FStar.Tactics.PatternMatching.abspat_binder_kind", "FStar.Reflection.Types.typ", "FStar.Tactics.PatternMatching.Mkabspat_argspec", "FStar.Tactics.NamedView.binder_to_binding", "FStar.Tactics.Util.fold_left", "FStar.Reflection.Types.term", "Prims.Cons", "FStar.Tactics.PatternMatching.pattern_of_term", "FStar.Pervasives.Native.option", "FStar.Pervasives.Native.Some", "FStar.Tactics.PatternMatching.string_of_abspat_binder_kind", "FStar.Tactics.V2.Builtins.term_to_string", "FStar.Tactics.PatternMatching.name_of_named_binder", "Prims.Nil", "FStar.Pervasives.Native.None", "FStar.Pervasives.Native.Mktuple4", "FStar.Tactics.PatternMatching.classify_abspat_binder", "FStar.Tactics.PatternMatching.type_of_named_binder", "FStar.String.concat", "FStar.Tactics.PatternMatching.binders_and_body_of_abs", "FStar.Tactics.PatternMatching.cleanup_abspat" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val matching_problem_of_abs (tm: term) : Tac (matching_problem * abspat_continuation)
[]
FStar.Tactics.PatternMatching.matching_problem_of_abs
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
tm: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.matching_problem * FStar.Tactics.PatternMatching.abspat_continuation)
{ "end_col": 18, "end_line": 673, "start_col": 52, "start_line": 632 }
FStar.Tactics.Effect.Tac
val solve_mp_for_single_hyp (#a: _) (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: (matching_solution -> Tac a)) (part_sol: matching_solution) : Tac a
[ { "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 } ]
false
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)
val solve_mp_for_single_hyp (#a: _) (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: (matching_solution -> Tac a)) (part_sol: matching_solution) : Tac a 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 =
true
null
false
match hypotheses with | [] -> fail #a "No matching hypothesis" | h :: hs -> or_else (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)
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.PatternMatching.pattern", "Prims.list", "FStar.Tactics.PatternMatching.hypothesis", "FStar.Tactics.PatternMatching.matching_solution", "FStar.Tactics.V2.Derived.fail", "FStar.Tactics.V2.Derived.or_else", "Prims.unit", "FStar.Tactics.PatternMatching.match_exception", "Prims.string", "Prims.op_Hat", "FStar.Tactics.PatternMatching.string_of_match_exception", "FStar.Tactics.PatternMatching.bindings", "FStar.Tactics.PatternMatching.Mkmatching_solution", "FStar.Pervasives.Native.tuple2", "Prims.Cons", "FStar.Pervasives.Native.Mktuple2", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_hyps", "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.interp_pattern_aux", "FStar.Tactics.PatternMatching.__proj__Mkmatching_solution__item__ms_vars", "FStar.Tactics.V2.Derived.type_of_binding", "FStar.Tactics.PatternMatching.solve_mp_for_single_hyp" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val solve_mp_for_single_hyp (#a: _) (name: varname) (pat: pattern) (hypotheses: list hypothesis) (body: (matching_solution -> Tac a)) (part_sol: matching_solution) : Tac a
[ "recursion" ]
FStar.Tactics.PatternMatching.solve_mp_for_single_hyp
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
name: FStar.Tactics.PatternMatching.varname -> pat: FStar.Tactics.PatternMatching.pattern -> hypotheses: Prims.list FStar.Tactics.PatternMatching.hypothesis -> body: (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a) -> part_sol: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a
{ "end_col": 59, "end_line": 453, "start_col": 2, "start_line": 440 }
FStar.Tactics.Effect.Tac
val classify_abspat_binder (b: binder) : Tac (abspat_binder_kind * term)
[ { "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 } ]
false
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
val classify_abspat_binder (b: binder) : Tac (abspat_binder_kind * term) let classify_abspat_binder (b: binder) : Tac (abspat_binder_kind * term) =
true
null
false
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
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "FStar.Tactics.NamedView.binder", "FStar.Tactics.PatternMatching.varname", "FStar.Tactics.NamedView.term", "FStar.Pervasives.Native.Mktuple2", "FStar.Tactics.PatternMatching.abspat_binder_kind", "FStar.Tactics.PatternMatching.ABKHyp", "FStar.Pervasives.Native.tuple2", "FStar.Tactics.PatternMatching.bindings", "FStar.Tactics.V2.Derived.fail", "FStar.Tactics.PatternMatching.match_exception", "FStar.Tactics.PatternMatching.ABKGoal", "FStar.Tactics.PatternMatching.ABKVar", "FStar.Tactics.PatternMatching.match_res", "FStar.Tactics.PatternMatching.interp_pattern", "FStar.Tactics.PatternMatching.type_of_named_binder", "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.PApp", "FStar.Tactics.PatternMatching.PQn", "FStar.Tactics.PatternMatching.goal_qn", "FStar.Tactics.PatternMatching.PVar", "FStar.Tactics.PatternMatching.hyp_qn", "Prims.string" ]
[]
(* 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
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val classify_abspat_binder (b: binder) : Tac (abspat_binder_kind * term)
[]
FStar.Tactics.PatternMatching.classify_abspat_binder
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
b: FStar.Tactics.NamedView.binder -> FStar.Tactics.Effect.Tac (FStar.Tactics.PatternMatching.abspat_binder_kind * FStar.Tactics.NamedView.term)
{ "end_col": 34, "end_line": 600, "start_col": 74, "start_line": 587 }
FStar.Tactics.Effect.Tac
val solve_mp (#a: _) (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: (matching_solution -> Tac a)) : Tac a
[ { "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 } ]
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
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 =
true
null
false
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
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "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" ]
[]
(* 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)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val solve_mp (#a: _) (problem: matching_problem) (hypotheses: list hypothesis) (goal: term) (body: (matching_solution -> Tac a)) : Tac a
[]
FStar.Tactics.PatternMatching.solve_mp
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
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
{ "end_col": 62, "end_line": 485, "start_col": 13, "start_line": 477 }
Prims.Tot
[ { "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 } ]
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 ^ ")"
let rec string_of_pattern =
false
null
false
function | PVar x -> "?" ^ x | PQn qn -> qn | PType -> "Type" | PApp l r -> "(" ^ string_of_pattern l ^ " " ^ string_of_pattern r ^ ")"
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.PatternMatching.pattern", "FStar.Tactics.PatternMatching.varname", "Prims.op_Hat", "FStar.Tactics.PatternMatching.qn", "FStar.Tactics.PatternMatching.string_of_pattern", "Prims.string" ]
[]
(* 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"
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val string_of_pattern : _: FStar.Tactics.PatternMatching.pattern -> Prims.string
[ "recursion" ]
FStar.Tactics.PatternMatching.string_of_pattern
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
_: FStar.Tactics.PatternMatching.pattern -> Prims.string
{ "end_col": 44, "end_line": 183, "start_col": 28, "start_line": 178 }
FStar.Tactics.Effect.Tac
val mustfail (#a: _) (t: (unit -> Tac a)) (message: string) : Tac unit
[ { "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 } ]
false
let mustfail #a (t: unit -> Tac a) (message: string) : Tac unit = match trytac t with | Some _ -> fail message | None -> ()
val mustfail (#a: _) (t: (unit -> Tac a)) (message: string) : Tac unit let mustfail #a (t: (unit -> Tac a)) (message: string) : Tac unit =
true
null
false
match trytac t with | Some _ -> fail message | None -> ()
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[]
[ "Prims.unit", "Prims.string", "FStar.Tactics.V2.Derived.fail", "FStar.Pervasives.Native.option", "FStar.Tactics.V2.Derived.trytac" ]
[]
(* 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. **)
false
false
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val mustfail (#a: _) (t: (unit -> Tac a)) (message: string) : Tac unit
[]
FStar.Tactics.PatternMatching.mustfail
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
t: (_: Prims.unit -> FStar.Tactics.Effect.Tac a) -> message: Prims.string -> FStar.Tactics.Effect.Tac Prims.unit
{ "end_col": 16, "end_line": 132, "start_col": 4, "start_line": 130 }
Prims.Tot
[ { "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 } ]
false
let string_of_abspat_binder_kind = function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal"
let string_of_abspat_binder_kind =
false
null
false
function | ABKVar _ -> "varname" | ABKHyp -> "hyp" | ABKGoal -> "goal"
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.PatternMatching.abspat_binder_kind", "FStar.Reflection.Types.typ", "Prims.string" ]
[]
(* 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
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val string_of_abspat_binder_kind : _: FStar.Tactics.PatternMatching.abspat_binder_kind -> Prims.string
[]
FStar.Tactics.PatternMatching.string_of_abspat_binder_kind
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
_: FStar.Tactics.PatternMatching.abspat_binder_kind -> Prims.string
{ "end_col": 21, "end_line": 573, "start_col": 35, "start_line": 570 }
Prims.Tot
[ { "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 } ]
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
let locate_fn_of_binder_kind binder_kind =
false
null
false
match binder_kind with | ABKVar _ -> `ms_locate_var | ABKHyp -> `ms_locate_hyp | ABKGoal -> `ms_locate_unit
{ "checked_file": "FStar.Tactics.PatternMatching.fst.checked", "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" }
[ "total" ]
[ "FStar.Tactics.PatternMatching.abspat_binder_kind", "FStar.Reflection.Types.typ", "FStar.Reflection.Types.term" ]
[]
(* 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. **)
false
true
FStar.Tactics.PatternMatching.fst
{ "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" }
null
val locate_fn_of_binder_kind : binder_kind: FStar.Tactics.PatternMatching.abspat_binder_kind -> FStar.Reflection.Types.term
[]
FStar.Tactics.PatternMatching.locate_fn_of_binder_kind
{ "file_name": "ulib/FStar.Tactics.PatternMatching.fst", "git_rev": "f4cbb7a38d67eeb13fbdb2f4fb8a44a65cbcdc1f", "git_url": "https://github.com/FStarLang/FStar.git", "project_name": "FStar" }
binder_kind: FStar.Tactics.PatternMatching.abspat_binder_kind -> FStar.Reflection.Types.term
{ "end_col": 31, "end_line": 694, "start_col": 2, "start_line": 691 }
Prims.Tot
[ { "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 } ]
false
let op_String_Access (#hsz:pos) = S.index #(padded_hash #hsz)
let op_String_Access (#hsz: pos) =
false
null
false
S.index #(padded_hash #hsz)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "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" ]
[]
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
false
false
MerkleTree.Spec.fst
{ "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" }
null
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
[]
MerkleTree.Spec.op_String_Access
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
s: FStar.Seq.Base.seq MerkleTree.Spec.padded_hash -> i: Prims.nat{i < FStar.Seq.Base.length s} -> MerkleTree.Spec.padded_hash
{ "end_col": 68, "end_line": 53, "start_col": 41, "start_line": 53 }
Prims.Tot
val hashes (#hsz:pos): Type0
[ { "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 } ]
false
let hashes #hsz = S.seq (padded_hash #hsz)
val hashes (#hsz:pos): Type0 let hashes #hsz =
false
null
false
S.seq (padded_hash #hsz)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total" ]
[ "Prims.pos", "FStar.Seq.Base.seq", "MerkleTree.Spec.padded_hash" ]
[]
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
false
true
MerkleTree.Spec.fst
{ "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" }
null
val hashes (#hsz:pos): Type0
[]
MerkleTree.Spec.hashes
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
Type0
{ "end_col": 42, "end_line": 46, "start_col": 18, "start_line": 46 }
Prims.GTot
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
[ { "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 } ]
false
let mt_verify #hsz #f #n p idx h rt = rt == mt_verify_ #_ #f p idx 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 =
false
null
false
rt == mt_verify_ #_ #f p idx h
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "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" ]
[]
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
false
false
MerkleTree.Spec.fst
{ "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" }
null
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
[]
MerkleTree.Spec.mt_verify
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
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
{ "end_col": 32, "end_line": 274, "start_col": 2, "start_line": 274 }
Prims.Tot
val pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Type0
[ { "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 } ]
false
let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad)
val pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Type0 let pad_hashes #hsz #f hs =
false
null
false
S.equal hs (S.create (S.length hs) HPad)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "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" ]
[]
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 -> hs:hashes #hsz -> Type0
false
false
MerkleTree.Spec.fst
{ "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" }
null
val pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Type0
[]
MerkleTree.Spec.pad_hashes
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
hs: MerkleTree.Spec.hashes -> Type0
{ "end_col": 42, "end_line": 368, "start_col": 2, "start_line": 368 }
Prims.GTot
val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)
[ { "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 } ]
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)
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 =
false
null
false
allow_inversion (padded_hash #hsz); match lh, rh with | HPad, _ -> HPad | _, HPad -> lh | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "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" ]
[]
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)
false
false
MerkleTree.Spec.fst
{ "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" }
null
val padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)
[]
MerkleTree.Spec.padded_hash_fun
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
f: MerkleTree.Spec.hash_fun_t -> lh: MerkleTree.Spec.padded_hash -> rh: MerkleTree.Spec.padded_hash -> Prims.GTot MerkleTree.Spec.padded_hash
{ "end_col": 42, "end_line": 42, "start_col": 2, "start_line": 38 }
Prims.GTot
val mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz)
[ { "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 } ]
false
let mt_get #_ #_ mt idx = S.index mt idx
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 =
false
null
false
S.index mt idx
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "sometrivial" ]
[ "Prims.pos", "Prims.nat", "MerkleTree.Spec.merkle_tree", "Prims.b2t", "Prims.op_LessThan", "Prims.pow2", "FStar.Seq.Base.index", "MerkleTree.Spec.padded_hash" ]
[]
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}
false
false
MerkleTree.Spec.fst
{ "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" }
null
val mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz)
[]
MerkleTree.Spec.mt_get
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> idx: Prims.nat{idx < Prims.pow2 n} -> Prims.GTot MerkleTree.Spec.padded_hash
{ "end_col": 40, "end_line": 51, "start_col": 26, "start_line": 51 }
Prims.Tot
val rpmt_raws: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #hsz #f n i -> S.seq (hash #hsz)
[ { "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 } ]
false
let rpmt_raws #hsz #f #n #i mt = raw_hashes_raws #_ #f (S.slice mt 0 i)
val rpmt_raws: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #hsz #f n i -> S.seq (hash #hsz) let rpmt_raws #hsz #f #n #i mt =
false
null
false
raw_hashes_raws #_ #f (S.slice mt 0 i)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.pow2", "MerkleTree.Spec.rpmt", "MerkleTree.Spec.raw_hashes_raws", "FStar.Seq.Base.slice", "MerkleTree.Spec.padded_hash", "FStar.Seq.Base.seq", "MerkleTree.Spec.hash" ]
[]
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 -> hs:hashes #hsz -> Type0 let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad) val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i)) let rec pad_hashes_slice #hsz #f hs i j = if i = j then () else pad_hashes_slice #_ #f hs (i + 1) j /// Right-padded Merkle tree, a tree refinement let rpmt (#hsz:pos) (#f:hash_fun_t) (n:nat) (i:nat{i <= pow2 n}) = mt:merkle_tree #hsz n { raw_hashes #_ #f (S.slice mt 0 i) /\ pad_hashes #_ #f (S.slice mt i (S.length mt)) }
false
false
MerkleTree.Spec.fst
{ "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" }
null
val rpmt_raws: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #hsz #f n i -> S.seq (hash #hsz)
[]
MerkleTree.Spec.rpmt_raws
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.rpmt n i -> FStar.Seq.Base.seq MerkleTree.Spec.hash
{ "end_col": 71, "end_line": 388, "start_col": 33, "start_line": 388 }
FStar.Pervasives.Lemma
val rpmt_get_root_raw: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i > 0 <==> HRaw? (mt_get_root #_ #f mt))
[ { "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 } ]
false
let rpmt_get_root_raw #hsz #f #n #i mt = allow_inversion (padded_hash #hsz); rpmt_get_root_pad #_ #f mt
val rpmt_get_root_raw: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i > 0 <==> HRaw? (mt_get_root #_ #f mt)) let rpmt_get_root_raw #hsz #f #n #i mt =
false
null
true
allow_inversion (padded_hash #hsz); rpmt_get_root_pad #_ #f mt
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.pow2", "MerkleTree.Spec.rpmt", "MerkleTree.Spec.rpmt_get_root_pad", "Prims.unit", "FStar.Pervasives.allow_inversion", "MerkleTree.Spec.padded_hash" ]
[]
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 -> hs:hashes #hsz -> Type0 let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad) val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i)) let rec pad_hashes_slice #hsz #f hs i j = if i = j then () else pad_hashes_slice #_ #f hs (i + 1) j /// Right-padded Merkle tree, a tree refinement let rpmt (#hsz:pos) (#f:hash_fun_t) (n:nat) (i:nat{i <= pow2 n}) = mt:merkle_tree #hsz n { raw_hashes #_ #f (S.slice mt 0 i) /\ pad_hashes #_ #f (S.slice mt i (S.length mt)) } val rpmt_raws: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #hsz #f n i -> S.seq (hash #hsz) let rpmt_raws #hsz #f #n #i mt = raw_hashes_raws #_ #f (S.slice mt 0 i) val rpmt_i_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:rpmt #hsz #f n 0 -> Lemma (S.equal mt (S.create (pow2 n) (HPad #hsz))) let rpmt_i_0 #hsz #f #n mt = () val rpmt_left: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> #i:nat{i <= pow2 n} -> rpmt #hsz #f n i -> rpmt #hsz #f (n-1) (if i <= pow2 (n-1) then i else pow2 (n-1)) let rpmt_left #hsz #f #n #i mt = if i <= pow2 (n-1) then pad_hashes_slice #_ #f (S.slice mt i (S.length mt)) 0 (pow2 (n-1) - i) else raw_hashes_slice #_ #f (S.slice mt 0 i) 0 (pow2 (n-1)); mt_left mt #push-options "--z3rlimit 40" val rpmt_right: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> #i:nat{i <= pow2 n} -> rpmt #hsz #f n i -> rpmt #_ #f (n-1) (if i <= pow2 (n-1) then 0 else i - pow2 (n-1)) let rpmt_right #hsz #f #n #i mt = if i <= pow2 (n-1) then pad_hashes_slice #_ #f (S.slice mt i (S.length mt)) (pow2 (n-1) - i) (pow2 n - i) else raw_hashes_slice #_ #f (S.slice mt 0 i) (pow2 (n-1)) i; mt_right mt /// Two right-padded Merkle trees collide when /// 1) they have the same height (`n`) and number of raw hashes (`i`), /// 2) their contents differ, and /// 3) their roots are same. // fournet: we may want to work towards removing 1) using a hash prefix noeq type mt_collide (#hsz:pos) (#f:hash_fun_t #hsz) (n:nat) (i:nat{i <= pow2 n}) = | Collision: mt1:rpmt #_ #f n i -> mt2:rpmt #_ #f n i { mt1 =!= mt2 /\ mt_get_root #_ #f #_ mt1 == mt_get_root #_ #f #_ mt2 } -> mt_collide #_ #f n i noeq type hash2_raw_collide = | Collision2: #hsz:pos -> #f:hash_fun_t #hsz -> lh1:hash -> rh1:hash -> lh2:hash -> rh2:hash { (lh1 =!= lh2 \/ rh1 =!= rh2) /\ f lh1 rh1 == f lh2 rh2 } -> hash2_raw_collide /// Auxiliary lemmas for the proof val rpmt_pad_hashes_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> pad_hashes #_ #f mt ) let rpmt_pad_hashes_0 #_ #_ #n #i mt = () val rpmt_pad_hashes_index_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? mt.[0]) let rpmt_pad_hashes_index_0 #_ #_ #n #i mt = () val mt_get_root_pad_index_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> Lemma (HPad? mt.[0] <==> HPad? (mt_get_root #_ #f mt)) let rec mt_get_root_pad_index_0 #hsz #f #n (mt:merkle_tree #hsz n) = if n = 0 then () else let mt:merkle_tree #hsz (n-1) = mt_next_lv #_ #f #n mt in mt_get_root_pad_index_0 #_ #f #(n-1) mt #pop-options val rpmt_get_root_pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? (mt_get_root #_ #f mt)) let rpmt_get_root_pad_hashes #_ #f #n #i mt = rpmt_pad_hashes_index_0 #_ #f mt; mt_get_root_pad_index_0 #_ #f mt val rpmt_get_root_pad: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> HPad? (mt_get_root #_ #f mt)) let rpmt_get_root_pad #_ #f #n #i mt = rpmt_get_root_pad_hashes #_ #f mt; rpmt_pad_hashes_0 #_ #f mt val rpmt_get_root_raw: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i > 0 <==> HRaw? (mt_get_root #_ #f mt))
false
false
MerkleTree.Spec.fst
{ "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" }
null
val rpmt_get_root_raw: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i > 0 <==> HRaw? (mt_get_root #_ #f mt))
[]
MerkleTree.Spec.rpmt_get_root_raw
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.rpmt n i -> FStar.Pervasives.Lemma (ensures i > 0 <==> HRaw? (MerkleTree.Spec.mt_get_root mt))
{ "end_col": 28, "end_line": 481, "start_col": 2, "start_line": 480 }
Prims.GTot
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)
[ { "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 } ]
false
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 -> GTot (padded_hash #hsz) let rec mt_verify_ #hsz #f #n p idx h =
false
null
false
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)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "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.op_Equality", "Prims.int", "Prims.bool", "MerkleTree.Spec.mt_verify_", "Prims.op_Subtraction", "FStar.Seq.Properties.tail", "Prims.op_Division", "Prims.op_Modulus", "MerkleTree.Spec.padded_hash_fun", "FStar.Seq.Properties.head", "Prims.l_or", "Prims.precedes", "Prims.l_and", "Prims.op_Equals_Equals_Equals" ]
[]
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)
false
false
MerkleTree.Spec.fst
{ "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" }
null
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)
[ "recursion" ]
MerkleTree.Spec.mt_verify_
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
p: MerkleTree.Spec.path n -> idx: Prims.nat{idx < Prims.pow2 n} -> h: MerkleTree.Spec.padded_hash -> Prims.GTot MerkleTree.Spec.padded_hash
{ "end_col": 58, "end_line": 268, "start_col": 2, "start_line": 264 }
Prims.Tot
val sha256_compress: hash_fun_t #32
[ { "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 } ]
false
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 ()
val sha256_compress: hash_fun_t #32 let sha256_compress src1 src2 =
false
null
false
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 ()
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total" ]
[ "MerkleTree.Spec.hash", "Spec.Agile.Hash.finish", "Spec.Hash.Definitions.words_state", "Spec.Agile.Hash.update", "FStar.Seq.Base.append", "Lib.IntTypes.uint8", "Spec.Hash.Definitions.init_t", "Spec.Agile.Hash.init", "Spec.Hash.Definitions.hash_alg", "Spec.Hash.Definitions.SHA2_256" ]
[]
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)
false
false
MerkleTree.Spec.fst
{ "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" }
null
val sha256_compress: hash_fun_t #32
[]
MerkleTree.Spec.sha256_compress
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
MerkleTree.Spec.hash_fun_t
{ "end_col": 40, "end_line": 23, "start_col": 31, "start_line": 18 }
Prims.Tot
[ { "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 } ]
false
let rpmt (#hsz:pos) (#f:hash_fun_t) (n:nat) (i:nat{i <= pow2 n}) = mt:merkle_tree #hsz n { raw_hashes #_ #f (S.slice mt 0 i) /\ pad_hashes #_ #f (S.slice mt i (S.length mt)) }
let rpmt (#hsz: pos) (#f: hash_fun_t) (n: nat) (i: nat{i <= pow2 n}) =
false
null
false
mt: merkle_tree #hsz n {raw_hashes #_ #f (S.slice mt 0 i) /\ pad_hashes #_ #f (S.slice mt i (S.length mt))}
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.pow2", "MerkleTree.Spec.merkle_tree", "Prims.l_and", "MerkleTree.Spec.raw_hashes", "FStar.Seq.Base.slice", "MerkleTree.Spec.padded_hash", "MerkleTree.Spec.pad_hashes", "FStar.Seq.Base.length" ]
[]
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 -> hs:hashes #hsz -> Type0 let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad) val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i)) let rec pad_hashes_slice #hsz #f hs i j = if i = j then () else pad_hashes_slice #_ #f hs (i + 1) j /// Right-padded Merkle tree, a tree refinement
false
false
MerkleTree.Spec.fst
{ "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" }
null
val rpmt : n: Prims.nat -> i: Prims.nat{i <= Prims.pow2 n} -> Type0
[]
MerkleTree.Spec.rpmt
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
n: Prims.nat -> i: Prims.nat{i <= Prims.pow2 n} -> Type0
{ "end_col": 51, "end_line": 385, "start_col": 2, "start_line": 383 }
Prims.Tot
val raw_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Tot Type0 (decreases (S.length hs))
[ { "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 } ]
false
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: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Tot Type0 (decreases (S.length hs)) let rec raw_hashes #hsz #f hs =
false
null
false
if S.length hs = 0 then True else (HRaw? (S.head hs) /\ raw_hashes #_ #f (S.tail hs))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total", "" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.hashes", "Prims.op_Equality", "Prims.int", "FStar.Seq.Base.length", "MerkleTree.Spec.padded_hash", "Prims.l_True", "Prims.bool", "Prims.l_and", "Prims.b2t", "MerkleTree.Spec.uu___is_HRaw", "FStar.Seq.Properties.head", "MerkleTree.Spec.raw_hashes", "FStar.Seq.Properties.tail" ]
[]
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))
false
false
MerkleTree.Spec.fst
{ "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" }
null
val raw_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes #hsz -> Tot Type0 (decreases (S.length hs))
[ "recursion" ]
MerkleTree.Spec.raw_hashes
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
hs: MerkleTree.Spec.hashes -> Prims.Tot Type0
{ "end_col": 58, "end_line": 331, "start_col": 2, "start_line": 330 }
FStar.Pervasives.Lemma
val rpmt_get_root_pad: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> HPad? (mt_get_root #_ #f mt))
[ { "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 } ]
false
let rpmt_get_root_pad #_ #f #n #i mt = rpmt_get_root_pad_hashes #_ #f mt; rpmt_pad_hashes_0 #_ #f mt
val rpmt_get_root_pad: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> HPad? (mt_get_root #_ #f mt)) let rpmt_get_root_pad #_ #f #n #i mt =
false
null
true
rpmt_get_root_pad_hashes #_ #f mt; rpmt_pad_hashes_0 #_ #f mt
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.pow2", "MerkleTree.Spec.rpmt", "MerkleTree.Spec.rpmt_pad_hashes_0", "Prims.unit", "MerkleTree.Spec.rpmt_get_root_pad_hashes" ]
[]
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 -> hs:hashes #hsz -> Type0 let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad) val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i)) let rec pad_hashes_slice #hsz #f hs i j = if i = j then () else pad_hashes_slice #_ #f hs (i + 1) j /// Right-padded Merkle tree, a tree refinement let rpmt (#hsz:pos) (#f:hash_fun_t) (n:nat) (i:nat{i <= pow2 n}) = mt:merkle_tree #hsz n { raw_hashes #_ #f (S.slice mt 0 i) /\ pad_hashes #_ #f (S.slice mt i (S.length mt)) } val rpmt_raws: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #hsz #f n i -> S.seq (hash #hsz) let rpmt_raws #hsz #f #n #i mt = raw_hashes_raws #_ #f (S.slice mt 0 i) val rpmt_i_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:rpmt #hsz #f n 0 -> Lemma (S.equal mt (S.create (pow2 n) (HPad #hsz))) let rpmt_i_0 #hsz #f #n mt = () val rpmt_left: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> #i:nat{i <= pow2 n} -> rpmt #hsz #f n i -> rpmt #hsz #f (n-1) (if i <= pow2 (n-1) then i else pow2 (n-1)) let rpmt_left #hsz #f #n #i mt = if i <= pow2 (n-1) then pad_hashes_slice #_ #f (S.slice mt i (S.length mt)) 0 (pow2 (n-1) - i) else raw_hashes_slice #_ #f (S.slice mt 0 i) 0 (pow2 (n-1)); mt_left mt #push-options "--z3rlimit 40" val rpmt_right: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> #i:nat{i <= pow2 n} -> rpmt #hsz #f n i -> rpmt #_ #f (n-1) (if i <= pow2 (n-1) then 0 else i - pow2 (n-1)) let rpmt_right #hsz #f #n #i mt = if i <= pow2 (n-1) then pad_hashes_slice #_ #f (S.slice mt i (S.length mt)) (pow2 (n-1) - i) (pow2 n - i) else raw_hashes_slice #_ #f (S.slice mt 0 i) (pow2 (n-1)) i; mt_right mt /// Two right-padded Merkle trees collide when /// 1) they have the same height (`n`) and number of raw hashes (`i`), /// 2) their contents differ, and /// 3) their roots are same. // fournet: we may want to work towards removing 1) using a hash prefix noeq type mt_collide (#hsz:pos) (#f:hash_fun_t #hsz) (n:nat) (i:nat{i <= pow2 n}) = | Collision: mt1:rpmt #_ #f n i -> mt2:rpmt #_ #f n i { mt1 =!= mt2 /\ mt_get_root #_ #f #_ mt1 == mt_get_root #_ #f #_ mt2 } -> mt_collide #_ #f n i noeq type hash2_raw_collide = | Collision2: #hsz:pos -> #f:hash_fun_t #hsz -> lh1:hash -> rh1:hash -> lh2:hash -> rh2:hash { (lh1 =!= lh2 \/ rh1 =!= rh2) /\ f lh1 rh1 == f lh2 rh2 } -> hash2_raw_collide /// Auxiliary lemmas for the proof val rpmt_pad_hashes_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> pad_hashes #_ #f mt ) let rpmt_pad_hashes_0 #_ #_ #n #i mt = () val rpmt_pad_hashes_index_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? mt.[0]) let rpmt_pad_hashes_index_0 #_ #_ #n #i mt = () val mt_get_root_pad_index_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> Lemma (HPad? mt.[0] <==> HPad? (mt_get_root #_ #f mt)) let rec mt_get_root_pad_index_0 #hsz #f #n (mt:merkle_tree #hsz n) = if n = 0 then () else let mt:merkle_tree #hsz (n-1) = mt_next_lv #_ #f #n mt in mt_get_root_pad_index_0 #_ #f #(n-1) mt #pop-options val rpmt_get_root_pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? (mt_get_root #_ #f mt)) let rpmt_get_root_pad_hashes #_ #f #n #i mt = rpmt_pad_hashes_index_0 #_ #f mt; mt_get_root_pad_index_0 #_ #f mt val rpmt_get_root_pad: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> HPad? (mt_get_root #_ #f mt))
false
false
MerkleTree.Spec.fst
{ "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" }
null
val rpmt_get_root_pad: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> HPad? (mt_get_root #_ #f mt))
[]
MerkleTree.Spec.rpmt_get_root_pad
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.rpmt n i -> FStar.Pervasives.Lemma (ensures i = 0 <==> HPad? (MerkleTree.Spec.mt_get_root mt))
{ "end_col": 28, "end_line": 473, "start_col": 2, "start_line": 472 }
Prims.Tot
val mt_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)
[ { "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 } ]
false
let mt_right #_ #n mt = S.slice mt (pow2 (n-1)) (pow2 n)
val mt_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1) let mt_right #_ #n mt =
false
null
false
S.slice mt (pow2 (n - 1)) (pow2 n)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total" ]
[ "Prims.pos", "MerkleTree.Spec.merkle_tree", "FStar.Seq.Base.slice", "MerkleTree.Spec.padded_hash", "Prims.pow2", "Prims.op_Subtraction" ]
[]
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))
false
false
MerkleTree.Spec.fst
{ "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" }
null
val mt_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)
[]
MerkleTree.Spec.mt_right
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> MerkleTree.Spec.merkle_tree (n - 1)
{ "end_col": 56, "end_line": 61, "start_col": 24, "start_line": 61 }
Prims.GTot
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)
[ { "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 } ]
false
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_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 =
false
null
false
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))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "sometrivial" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "MerkleTree.Spec.merkle_tree", "Prims.b2t", "Prims.op_LessThan", "Prims.pow2", "Prims.op_Equality", "Prims.int", "FStar.Seq.Base.empty", "MerkleTree.Spec.padded_hash", "Prims.bool", "FStar.Seq.Properties.cons", "Prims.op_Modulus", "MerkleTree.Spec.op_String_Access", "Prims.op_Addition", "Prims.op_Subtraction", "MerkleTree.Spec.mt_get_path", "MerkleTree.Spec.mt_next_lv", "Prims.op_Division", "MerkleTree.Spec.path" ]
[]
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)
false
false
MerkleTree.Spec.fst
{ "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" }
null
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)
[ "recursion" ]
MerkleTree.Spec.mt_get_path
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> i: Prims.nat{i < Prims.pow2 n} -> Prims.GTot (MerkleTree.Spec.path n)
{ "end_col": 52, "end_line": 258, "start_col": 2, "start_line": 255 }
Prims.GTot
val mt_get_root: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> GTot (padded_hash #hsz)
[ { "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 } ]
false
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)
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 =
false
null
false
if n = 0 then mt.[ 0 ] else mt_get_root #_ #f (mt_next_lv #_ #f mt)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "sometrivial" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "MerkleTree.Spec.merkle_tree", "Prims.op_Equality", "Prims.int", "MerkleTree.Spec.op_String_Access", "Prims.bool", "MerkleTree.Spec.mt_get_root", "Prims.op_Subtraction", "MerkleTree.Spec.mt_next_lv", "MerkleTree.Spec.padded_hash" ]
[]
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)
false
false
MerkleTree.Spec.fst
{ "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" }
null
val mt_get_root: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> GTot (padded_hash #hsz)
[ "recursion" ]
MerkleTree.Spec.mt_get_root
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> Prims.GTot MerkleTree.Spec.padded_hash
{ "end_col": 46, "end_line": 230, "start_col": 2, "start_line": 229 }
FStar.Pervasives.Lemma
val rpmt_get_root_pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? (mt_get_root #_ #f mt))
[ { "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 } ]
false
let rpmt_get_root_pad_hashes #_ #f #n #i mt = rpmt_pad_hashes_index_0 #_ #f mt; mt_get_root_pad_index_0 #_ #f mt
val rpmt_get_root_pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? (mt_get_root #_ #f mt)) let rpmt_get_root_pad_hashes #_ #f #n #i mt =
false
null
true
rpmt_pad_hashes_index_0 #_ #f mt; mt_get_root_pad_index_0 #_ #f mt
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.pow2", "MerkleTree.Spec.rpmt", "MerkleTree.Spec.mt_get_root_pad_index_0", "Prims.unit", "MerkleTree.Spec.rpmt_pad_hashes_index_0" ]
[]
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 -> hs:hashes #hsz -> Type0 let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad) val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i)) let rec pad_hashes_slice #hsz #f hs i j = if i = j then () else pad_hashes_slice #_ #f hs (i + 1) j /// Right-padded Merkle tree, a tree refinement let rpmt (#hsz:pos) (#f:hash_fun_t) (n:nat) (i:nat{i <= pow2 n}) = mt:merkle_tree #hsz n { raw_hashes #_ #f (S.slice mt 0 i) /\ pad_hashes #_ #f (S.slice mt i (S.length mt)) } val rpmt_raws: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #hsz #f n i -> S.seq (hash #hsz) let rpmt_raws #hsz #f #n #i mt = raw_hashes_raws #_ #f (S.slice mt 0 i) val rpmt_i_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:rpmt #hsz #f n 0 -> Lemma (S.equal mt (S.create (pow2 n) (HPad #hsz))) let rpmt_i_0 #hsz #f #n mt = () val rpmt_left: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> #i:nat{i <= pow2 n} -> rpmt #hsz #f n i -> rpmt #hsz #f (n-1) (if i <= pow2 (n-1) then i else pow2 (n-1)) let rpmt_left #hsz #f #n #i mt = if i <= pow2 (n-1) then pad_hashes_slice #_ #f (S.slice mt i (S.length mt)) 0 (pow2 (n-1) - i) else raw_hashes_slice #_ #f (S.slice mt 0 i) 0 (pow2 (n-1)); mt_left mt #push-options "--z3rlimit 40" val rpmt_right: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> #i:nat{i <= pow2 n} -> rpmt #hsz #f n i -> rpmt #_ #f (n-1) (if i <= pow2 (n-1) then 0 else i - pow2 (n-1)) let rpmt_right #hsz #f #n #i mt = if i <= pow2 (n-1) then pad_hashes_slice #_ #f (S.slice mt i (S.length mt)) (pow2 (n-1) - i) (pow2 n - i) else raw_hashes_slice #_ #f (S.slice mt 0 i) (pow2 (n-1)) i; mt_right mt /// Two right-padded Merkle trees collide when /// 1) they have the same height (`n`) and number of raw hashes (`i`), /// 2) their contents differ, and /// 3) their roots are same. // fournet: we may want to work towards removing 1) using a hash prefix noeq type mt_collide (#hsz:pos) (#f:hash_fun_t #hsz) (n:nat) (i:nat{i <= pow2 n}) = | Collision: mt1:rpmt #_ #f n i -> mt2:rpmt #_ #f n i { mt1 =!= mt2 /\ mt_get_root #_ #f #_ mt1 == mt_get_root #_ #f #_ mt2 } -> mt_collide #_ #f n i noeq type hash2_raw_collide = | Collision2: #hsz:pos -> #f:hash_fun_t #hsz -> lh1:hash -> rh1:hash -> lh2:hash -> rh2:hash { (lh1 =!= lh2 \/ rh1 =!= rh2) /\ f lh1 rh1 == f lh2 rh2 } -> hash2_raw_collide /// Auxiliary lemmas for the proof val rpmt_pad_hashes_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (i = 0 <==> pad_hashes #_ #f mt ) let rpmt_pad_hashes_0 #_ #_ #n #i mt = () val rpmt_pad_hashes_index_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? mt.[0]) let rpmt_pad_hashes_index_0 #_ #_ #n #i mt = () val mt_get_root_pad_index_0: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> mt:merkle_tree #hsz n -> Lemma (HPad? mt.[0] <==> HPad? (mt_get_root #_ #f mt)) let rec mt_get_root_pad_index_0 #hsz #f #n (mt:merkle_tree #hsz n) = if n = 0 then () else let mt:merkle_tree #hsz (n-1) = mt_next_lv #_ #f #n mt in mt_get_root_pad_index_0 #_ #f #(n-1) mt #pop-options val rpmt_get_root_pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? (mt_get_root #_ #f mt))
false
false
MerkleTree.Spec.fst
{ "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" }
null
val rpmt_get_root_pad_hashes: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> #i:nat{i <= pow2 n} -> mt:rpmt #_ #f n i -> Lemma (pad_hashes #_ #f mt <==> HPad? (mt_get_root #_ #f mt))
[]
MerkleTree.Spec.rpmt_get_root_pad_hashes
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.rpmt n i -> FStar.Pervasives.Lemma (ensures MerkleTree.Spec.pad_hashes mt <==> HPad? (MerkleTree.Spec.mt_get_root mt))
{ "end_col": 34, "end_line": 465, "start_col": 2, "start_line": 464 }
Prims.GTot
val mt_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> GTot (merkle_tree #hsz (n-1))
[ { "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 } ]
false
let mt_next_lv #_ #f #n mt = hs_next_lv #_ #f #(pow2 (n-1)) mt
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 =
false
null
false
hs_next_lv #_ #f #(pow2 (n - 1)) mt
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "sometrivial" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.merkle_tree", "MerkleTree.Spec.hs_next_lv", "Prims.pow2", "Prims.op_Subtraction" ]
[]
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
false
false
MerkleTree.Spec.fst
{ "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" }
null
val mt_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> GTot (merkle_tree #hsz (n-1))
[]
MerkleTree.Spec.mt_next_lv
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> Prims.GTot (MerkleTree.Spec.merkle_tree (n - 1))
{ "end_col": 62, "end_line": 99, "start_col": 29, "start_line": 99 }
FStar.Pervasives.Lemma
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)
[ { "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 } ]
false
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_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 =
false
null
true
if i = 0 then () else raw_hashes_index #_ #f (S.tail hs) (i - 1)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma", "" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.hashes", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "FStar.Seq.Base.length", "MerkleTree.Spec.padded_hash", "Prims.op_Equality", "Prims.int", "Prims.bool", "MerkleTree.Spec.raw_hashes_index", "FStar.Seq.Properties.tail", "Prims.op_Subtraction", "Prims.unit" ]
[]
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)
false
false
MerkleTree.Spec.fst
{ "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" }
null
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)
[ "recursion" ]
MerkleTree.Spec.raw_hashes_index
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
hs: MerkleTree.Spec.hashes -> i: Prims.nat{i < FStar.Seq.Base.length hs} -> FStar.Pervasives.Lemma (requires MerkleTree.Spec.raw_hashes hs) (ensures HRaw? hs.[ i ]) (decreases i)
{ "end_col": 49, "end_line": 349, "start_col": 2, "start_line": 348 }
Prims.Tot
val mt_left: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)
[ { "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 } ]
false
let mt_left #_ #n mt = S.slice mt 0 (pow2 (n-1))
val mt_left: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1) let mt_left #_ #n mt =
false
null
false
S.slice mt 0 (pow2 (n - 1))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total" ]
[ "Prims.pos", "MerkleTree.Spec.merkle_tree", "FStar.Seq.Base.slice", "MerkleTree.Spec.padded_hash", "Prims.pow2", "Prims.op_Subtraction" ]
[]
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"
false
false
MerkleTree.Spec.fst
{ "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" }
null
val mt_left: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)
[]
MerkleTree.Spec.mt_left
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> MerkleTree.Spec.merkle_tree (n - 1)
{ "end_col": 48, "end_line": 58, "start_col": 23, "start_line": 58 }
FStar.Pervasives.Lemma
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))
[ { "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 } ]
false
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)
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 =
false
null
true
if i = j then () else (raw_hashes_index #_ #f hs i; raw_hashes_slice #_ #f hs (i + 1) j)
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma", "" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.hashes", "Prims.nat", "Prims.b2t", "Prims.op_AmpAmp", "Prims.op_LessThanOrEqual", "FStar.Seq.Base.length", "MerkleTree.Spec.padded_hash", "Prims.op_Equality", "Prims.bool", "MerkleTree.Spec.raw_hashes_slice", "Prims.op_Addition", "Prims.unit", "MerkleTree.Spec.raw_hashes_index" ]
[]
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))
false
false
MerkleTree.Spec.fst
{ "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" }
null
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))
[ "recursion" ]
MerkleTree.Spec.raw_hashes_slice
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
hs: MerkleTree.Spec.hashes -> i: Prims.nat -> j: Prims.nat{i <= j && j <= FStar.Seq.Base.length hs} -> FStar.Pervasives.Lemma (requires MerkleTree.Spec.raw_hashes hs) (ensures MerkleTree.Spec.raw_hashes (FStar.Seq.Base.slice hs i j)) (decreases j - i)
{ "end_col": 40, "end_line": 361, "start_col": 2, "start_line": 358 }
FStar.Pervasives.Lemma
val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i))
[ { "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 } ]
false
let rec pad_hashes_slice #hsz #f hs i j = if i = j then () else pad_hashes_slice #_ #f hs (i + 1) j
val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i)) let rec pad_hashes_slice #hsz #f hs i j =
false
null
true
if i = j then () else pad_hashes_slice #_ #f hs (i + 1) j
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma", "" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.hashes", "Prims.nat", "Prims.b2t", "Prims.op_AmpAmp", "Prims.op_LessThanOrEqual", "FStar.Seq.Base.length", "MerkleTree.Spec.padded_hash", "Prims.op_Equality", "Prims.bool", "MerkleTree.Spec.pad_hashes_slice", "Prims.op_Addition", "Prims.unit" ]
[]
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 -> hs:hashes #hsz -> Type0 let pad_hashes #hsz #f hs = S.equal hs (S.create (S.length hs) HPad) val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i))
false
false
MerkleTree.Spec.fst
{ "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" }
null
val pad_hashes_slice: #hsz:pos -> #f:hash_fun_t #hsz -> hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} -> Lemma (requires pad_hashes #_ #f hs) (ensures pad_hashes #_ #f (S.slice hs i j)) (decreases (j - i))
[ "recursion" ]
MerkleTree.Spec.pad_hashes_slice
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
hs: MerkleTree.Spec.hashes -> i: Prims.nat -> j: Prims.nat{i <= j && j <= FStar.Seq.Base.length hs} -> FStar.Pervasives.Lemma (requires MerkleTree.Spec.pad_hashes hs) (ensures MerkleTree.Spec.pad_hashes (FStar.Seq.Base.slice hs i j)) (decreases j - i)
{ "end_col": 42, "end_line": 378, "start_col": 2, "start_line": 377 }
Prims.Tot
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))
[ { "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 } ]
false
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_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 =
false
null
false
if S.length hs = 0 then S.empty else S.cons (HRaw?.hr (S.head hs)) (raw_hashes_raws #_ #f (S.tail hs))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "total", "" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.hashes", "MerkleTree.Spec.raw_hashes", "Prims.op_Equality", "Prims.int", "FStar.Seq.Base.length", "MerkleTree.Spec.padded_hash", "FStar.Seq.Base.empty", "MerkleTree.Spec.hash", "Prims.bool", "FStar.Seq.Properties.cons", "MerkleTree.Spec.__proj__HRaw__item__hr", "FStar.Seq.Properties.head", "MerkleTree.Spec.raw_hashes_raws", "FStar.Seq.Properties.tail", "FStar.Seq.Base.seq" ]
[]
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))
false
false
MerkleTree.Spec.fst
{ "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" }
null
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))
[ "recursion" ]
MerkleTree.Spec.raw_hashes_raws
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
hs: MerkleTree.Spec.hashes{MerkleTree.Spec.raw_hashes hs} -> Prims.Tot (FStar.Seq.Base.seq MerkleTree.Spec.hash)
{ "end_col": 72, "end_line": 339, "start_col": 2, "start_line": 338 }
FStar.Pervasives.Lemma
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)))
[ { "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 } ]
false
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_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 =
false
null
true
hs_next_lv_slice #_ #f #(pow2 (n - 1)) mt 0 (pow2 (n - 2))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "MerkleTree.Spec.merkle_tree", "MerkleTree.Spec.hs_next_lv_slice", "Prims.pow2", "Prims.op_Subtraction", "Prims.unit" ]
[]
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)))
false
false
MerkleTree.Spec.fst
{ "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" }
null
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)))
[]
MerkleTree.Spec.mt_next_lv_mt_left
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> FStar.Pervasives.Lemma (ensures FStar.Seq.Base.equal (MerkleTree.Spec.mt_next_lv (MerkleTree.Spec.mt_left mt)) (MerkleTree.Spec.mt_left (MerkleTree.Spec.mt_next_lv mt)))
{ "end_col": 56, "end_line": 104, "start_col": 2, "start_line": 104 }
FStar.Pervasives.Lemma
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)))
[ { "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 } ]
false
let mt_next_lv_equiv #hsz #f j n mt1 mt2 = hs_next_lv_equiv #_ #f j (pow2 (n-1)) mt1 mt2
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 =
false
null
true
hs_next_lv_equiv #_ #f j (pow2 (n - 1)) mt1 mt2
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThanOrEqual", "Prims.pow2", "MerkleTree.Spec.merkle_tree", "MerkleTree.Spec.hs_next_lv_equiv", "Prims.op_Subtraction", "Prims.unit" ]
[]
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)))
false
false
MerkleTree.Spec.fst
{ "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" }
null
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)))
[]
MerkleTree.Spec.mt_next_lv_equiv
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
j: Prims.nat -> n: Prims.pos{j <= Prims.pow2 n} -> mt1: MerkleTree.Spec.merkle_tree n -> mt2: MerkleTree.Spec.merkle_tree n -> FStar.Pervasives.Lemma (requires FStar.Seq.Base.equal (FStar.Seq.Base.slice mt1 0 j) (FStar.Seq.Base.slice mt2 0 j)) (ensures FStar.Seq.Base.equal (FStar.Seq.Base.slice (MerkleTree.Spec.mt_next_lv mt1) 0 (j / 2)) (FStar.Seq.Base.slice (MerkleTree.Spec.mt_next_lv mt2) 0 (j / 2)))
{ "end_col": 47, "end_line": 140, "start_col": 2, "start_line": 140 }
Prims.GTot
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
[ { "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 } ]
false
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 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 =
false
null
false
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))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "sometrivial" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "MerkleTree.Spec.hashes", "Prims.b2t", "Prims.op_Equality", "Prims.int", "FStar.Seq.Base.length", "MerkleTree.Spec.padded_hash", "FStar.Mul.op_Star", "Prims.l_Forall", "Prims.op_LessThan", "Prims.eq2", "FStar.Seq.Base.index", "MerkleTree.Spec.padded_hash_fun", "Prims.op_Addition" ]
[]
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
false
false
MerkleTree.Spec.fst
{ "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" }
null
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
[]
MerkleTree.Spec.hs_next_rel
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
n: Prims.nat -> hs: MerkleTree.Spec.hashes{FStar.Seq.Base.length hs = 2 * n} -> nhs: MerkleTree.Spec.hashes{FStar.Seq.Base.length nhs = n} -> Prims.GTot Type0
{ "end_col": 72, "end_line": 151, "start_col": 2, "start_line": 149 }
FStar.Pervasives.Lemma
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)))
[ { "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 } ]
false
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 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 =
false
null
true
hs_next_lv_slice #hsz #f #(pow2 (n - 1)) mt (pow2 (n - 2)) (pow2 (n - 1))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "Prims.b2t", "Prims.op_LessThan", "MerkleTree.Spec.merkle_tree", "MerkleTree.Spec.hs_next_lv_slice", "Prims.pow2", "Prims.op_Subtraction", "Prims.unit" ]
[]
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)))
false
false
MerkleTree.Spec.fst
{ "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" }
null
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)))
[]
MerkleTree.Spec.mt_next_lv_mt_right
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
mt: MerkleTree.Spec.merkle_tree n -> FStar.Pervasives.Lemma (ensures FStar.Seq.Base.equal (MerkleTree.Spec.mt_next_lv (MerkleTree.Spec.mt_right mt)) (MerkleTree.Spec.mt_right (MerkleTree.Spec.mt_next_lv mt)))
{ "end_col": 69, "end_line": 109, "start_col": 2, "start_line": 109 }
FStar.Pervasives.Lemma
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))
[ { "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 } ]
false
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_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 =
false
null
true
hs_next_rel_next_lv #_ #f (pow2 (n - 1)) mt nmt
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "lemma" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.merkle_tree", "Prims.op_Subtraction", "MerkleTree.Spec.hs_next_rel_next_lv", "Prims.pow2", "Prims.unit" ]
[]
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))
false
false
MerkleTree.Spec.fst
{ "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" }
null
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))
[]
MerkleTree.Spec.mt_next_rel_next_lv
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
n: Prims.pos -> mt: MerkleTree.Spec.merkle_tree n -> nmt: MerkleTree.Spec.merkle_tree (n - 1) -> FStar.Pervasives.Lemma (requires MerkleTree.Spec.mt_next_rel n mt nmt) (ensures FStar.Seq.Base.equal nmt (MerkleTree.Spec.mt_next_lv mt))
{ "end_col": 47, "end_line": 183, "start_col": 2, "start_line": 183 }
Prims.GTot
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})
[ { "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 } ]
false
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: #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 =
false
null
false
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)))
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "sometrivial" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "Prims.nat", "MerkleTree.Spec.hashes", "Prims.b2t", "Prims.op_Equality", "Prims.int", "FStar.Seq.Base.length", "MerkleTree.Spec.padded_hash", "FStar.Mul.op_Star", "FStar.Seq.Base.empty", "Prims.bool", "FStar.Seq.Properties.cons", "MerkleTree.Spec.padded_hash_fun", "MerkleTree.Spec.op_String_Access", "MerkleTree.Spec.hs_next_lv", "Prims.op_Subtraction", "FStar.Seq.Base.slice" ]
[]
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})
false
false
MerkleTree.Spec.fst
{ "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" }
null
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})
[ "recursion" ]
MerkleTree.Spec.hs_next_lv
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
hs: MerkleTree.Spec.hashes{FStar.Seq.Base.length hs = 2 * n} -> Prims.GTot (nhs: MerkleTree.Spec.hashes{FStar.Seq.Base.length nhs = n})
{ "end_col": 60, "end_line": 72, "start_col": 2, "start_line": 69 }
Prims.GTot
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
[ { "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 } ]
false
let mt_next_rel #hsz #f n mt nmt = hs_next_rel #hsz #f (pow2 (n-1)) mt nmt
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 =
false
null
false
hs_next_rel #hsz #f (pow2 (n - 1)) mt nmt
{ "checked_file": "MerkleTree.Spec.fst.checked", "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" }
[ "sometrivial" ]
[ "Prims.pos", "MerkleTree.Spec.hash_fun_t", "MerkleTree.Spec.merkle_tree", "Prims.op_Subtraction", "MerkleTree.Spec.hs_next_rel", "Prims.pow2" ]
[]
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
false
false
MerkleTree.Spec.fst
{ "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" }
null
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
[]
MerkleTree.Spec.mt_next_rel
{ "file_name": "src/MerkleTree.Spec.fst", "git_rev": "3b0f086655c145aa23f58a97259ebf4cf112a4a3", "git_url": "https://github.com/hacl-star/merkle-tree.git", "project_name": "merkle-tree" }
n: Prims.pos -> mt: MerkleTree.Spec.merkle_tree n -> nmt: MerkleTree.Spec.merkle_tree (n - 1) -> Prims.GTot Type0
{ "end_col": 41, "end_line": 160, "start_col": 2, "start_line": 160 }