messages
listlengths 2
2
|
|---|
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Type0\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule FStar.Stubs.Tactics.Types\n\nopen FStar.Stubs.Reflection.Types\ninclude FStar.Stubs.Tactics.Common\ninclude FStar.Stubs.TypeChecker.Core\n\nassume new type goal\nassume new type proofstate\n\n(* Returns the active goals *)\nval goals_of : proofstate -> list goal\n(* Returns the goals marked for SMT *)\nval smt_goals_of : proofstate -> list goal\n\n(* Inspecting a goal *)\nval goal_env : goal -> env\nval goal_type : goal -> typ\nval goal_witness : goal -> term\nval is_guard : goal -> bool (* A bit of helper info: did this goal come from a VC guard? *)\n\nval get_label : goal -> string\nval set_label : string -> goal -> goal\n\n(* Tracing *)\nval incr_depth : proofstate -> proofstate\nval decr_depth : proofstate -> proofstate\n(* [tracepoint] always returns true. We do not use unit to prevent\nerasure. *)\nval tracepoint : proofstate -> b:bool{b == true}\nval set_proofstate_range : proofstate -> FStar.Range.range -> proofstate\n\ntype direction =\n | TopDown\n | BottomUp\n\ntype ctrl_flag =\n | Continue\n | Skip\n | Abort\n\ntype guard_policy =\n | Goal // Add guards as (normal) goals\n | SMT // Add guards as SMT goals\n | SMTSync // Send guards to SMT immediately, will *log* errors (not raise) if anything fails\n | Force // Force guards without SMT\n | Drop // Drop guards, clearly unsound! careful!\n\n(* Typing reflection *)\nval non_informative_token (g:env) (t:typ) : Type0\nval subtyping_token (g:env) (t0 t1:typ) : Type0\nval equiv_token (g:env) (t0 t1:typ) : Type0\nval typing_token (g:env) (e:term) (c:tot_or_ghost & typ) : Type0\n\n(* Must be inline, this definition is not there in src/FStar.Tactics.Types *)\n\nPartial implementation:\nlet issues =\n \n"
},
{
"role": "assistant",
"content": "list FStar.Issue.issue"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Type0\nEffect: Prims.Tot\n\nContext:\nmodule Vale.Inline.X64.Fadd_inline\n\nopen Vale.X64.CPU_Features_s\nopen FStar.HyperStack.ST\nmodule B = LowStar.Buffer\nmodule HS = FStar.HyperStack\nopen Vale.Curve25519.Fast_defs\nopen FStar.Mul\n\nunfold\nlet u256 = b:B.buffer UInt64.t{B.length b == 4}\nunfold\nlet u512 = b:B.buffer UInt64.t{B.length b == 8}\n\nPartial implementation:\nlet u1024 =\n \n"
},
{
"role": "assistant",
"content": "b: B.buffer UInt64.t {B.length b == 16}"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Type0\nEffect: Prims.Tot\n\nContext:\nmodule Vale.Inline.X64.Fadd_inline\n\nopen Vale.X64.CPU_Features_s\nopen FStar.HyperStack.ST\nmodule B = LowStar.Buffer\nmodule HS = FStar.HyperStack\nopen Vale.Curve25519.Fast_defs\nopen FStar.Mul\n\nPartial implementation:\nlet u256 =\n \n"
},
{
"role": "assistant",
"content": "b: B.buffer UInt64.t {B.length b == 4}"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Type0\nEffect: Prims.Tot\n\nContext:\nmodule Vale.Inline.X64.Fadd_inline\n\nopen Vale.X64.CPU_Features_s\nopen FStar.HyperStack.ST\nmodule B = LowStar.Buffer\nmodule HS = FStar.HyperStack\nopen Vale.Curve25519.Fast_defs\nopen FStar.Mul\n\nunfold\nlet u256 = b:B.buffer UInt64.t{B.length b == 4}\n\nPartial implementation:\nlet u512 =\n \n"
},
{
"role": "assistant",
"content": "b: B.buffer UInt64.t {B.length b == 8}"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: d_sub: Pulse.Typing.st_sub g c1 c2\n -> Prims.dtuple2 FStar.Stubs.Reflection.Types.term\n (fun t ->\n FStar.Reflection.Typing.tot_typing (Pulse.Typing.elab_env g)\n t\n (Pulse.Elaborate.Core.simple_arr (Pulse.Elaborate.Pure.elab_comp c1)\n (Pulse.Elaborate.Pure.elab_comp c2)))\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\n\nlet elab_bind #g #x #c1 #c2 #c\n (bc:bind_comp g x c1 c2 c)\n (e1 e2:R.term)\n : R.term\n = let t1 = elab_term (comp_res c1) in\n let t2 = elab_term (comp_res c2) in\n match c1 with\n | C_ST _ ->\n mk_bind_stt\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STGhost _ ->\n mk_bind_ghost\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in \n mk_bind_atomic\n (comp_u c1)\n (comp_u c2)\n (elab_observability obs1)\n (elab_observability obs2)\n (elab_term (comp_inames c1))\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n \nlet elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term)\n : Tot R.term\n = match d with\n | Lift_STAtomic_ST _ _ ->\n let t = elab_term (comp_res c1) in\n mk_lift_atomic_stt\n (comp_u c1)\n (elab_term (comp_res c1))\n t\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\n | Lift_Observability _ c o2 ->\n let t = elab_term (comp_res c1) in\n mk_lift_observability\n (comp_u c1)\n (elab_observability (C_STAtomic?.obs c))\n (elab_observability o2)\n (elab_term (comp_inames c1))\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n \n | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) ->\n let t = elab_term (comp_res c1) in\n mk_lift_ghost_neutral\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n (elab_term reveal_a)\n\n | Lift_Neutral_Ghost _ c ->\n let t = elab_term (comp_res c1) in\n mk_lift_neutral_ghost\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\nlet intro_pure_tm (p:term) =\n let open Pulse.Reflection.Util in\n wtag (Some STT_Ghost) \n (Tm_STApp\n { head =\n tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid \"intro_pure\")))\n None\n p;\n arg_qual = None;\n arg = tm_fstar (`()) Range.range_0 })\n\nlet simple_arr (t1 t2 : R.term) : R.term =\n let b = R.pack_binder {\n sort = t1;\n ppname = Sealed.seal \"x\";\n qual = R.Q_Explicit;\n attrs = [] } in\n R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))\n\nPartial implementation:\nlet elab_st_sub (#g: env) (#c1 #c2: comp) (d_sub: st_sub g c1 c2)\n : Tot (t: R.term & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2))) =\n \n"
},
{
"role": "assistant",
"content": "RU.magic_s \"elab_st_sub\""
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n g: Pulse.Typing.Env.env ->\n p: Pulse.Syntax.Base.term ->\n typing: Pulse.Typing.tot_typing g p Pulse.Typing.tm_prop\n -> FStar.Tactics.Effect.Tac (Pulse.Typing.prop_validity g p)\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Checker.IntroPure\n\nopen Pulse.Syntax\nopen Pulse.Typing\nopen Pulse.Checker.Base\nopen Pulse.Checker.Prover\n\nmodule T = FStar.Tactics.V2\nmodule P = Pulse.Syntax.Printer\n\nlet check_prop (g:env) (p:term) \n : T.Tac (p:term & tot_typing g p tm_prop) =\n \n let p0 = p in\n let (| p, p_typing |) = Pulse.Checker.Pure.check_vprop g (tm_pure p) in\n match p.t with\n | Tm_Pure pp ->\n let prop_typing = Pulse.Typing.Metatheory.pure_typing_inversion #_ #pp p_typing in\n (| pp, prop_typing |)\n | _ ->\n fail g None\n (Printf.sprintf \"Impossible: check_intro_pure: checking a pure vprop %s returned a non-pure vprop %s,\\\n please file a bug-report\"\n (P.term_to_string (tm_pure p0))\n (P.term_to_string p))\n\nPartial implementation:\nlet check_prop_validity (g: env) (p: term) (typing: tot_typing g p tm_prop)\n : T.Tac (prop_validity g p) =\n \n"
},
{
"role": "assistant",
"content": "Pulse.Checker.Pure.check_prop_validity g p typing"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n b: LowStar.Buffer.buffer FStar.UInt64.t {LowStar.Monotonic.Buffer.length b == 4} ->\n h: FStar.Monotonic.HyperStack.mem\n -> Prims.GTot Prims.nat\nEffect: Prims.GTot\n\nContext:\nmodule Vale.Inline.X64.Fadd_inline\n\nopen Vale.X64.CPU_Features_s\nopen FStar.HyperStack.ST\nmodule B = LowStar.Buffer\nmodule HS = FStar.HyperStack\nopen Vale.Curve25519.Fast_defs\nopen FStar.Mul\n\nunfold\nlet u256 = b:B.buffer UInt64.t{B.length b == 4}\nunfold\nlet u512 = b:B.buffer UInt64.t{B.length b == 8}\nunfold\nlet u1024 = b:B.buffer UInt64.t{B.length b == 16}\n\nPartial implementation:\nlet as_nat (b: B.buffer UInt64.t {B.length b == 4}) (h: HS.mem) : GTot nat =\n \n"
},
{
"role": "assistant",
"content": "let s = B.as_seq h b in\nlet s0 = UInt64.v (Seq.index s 0) in\nlet s1 = UInt64.v (Seq.index s 1) in\nlet s2 = UInt64.v (Seq.index s 2) in\nlet s3 = UInt64.v (Seq.index s 3) in\npow2_four s0 s1 s2 s3"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Vale.Interop.Base.normal Vale.Stdcalls.X64.Aes.lowstar_key128_t\nEffect: Prims.Tot\n\nContext:\nmodule Vale.Stdcalls.X64.Aes\n\nopen FStar.Mul\nopen FStar.HyperStack.ST\nmodule HS = FStar.HyperStack\nmodule B = LowStar.Buffer\nmodule DV = LowStar.BufferView.Down\nmodule UV = LowStar.BufferView.Up\nopen Vale.Def.Types_s\n\nopen Vale.Interop.Base\nmodule IX64 = Vale.Interop.X64\nmodule VSig = Vale.AsLowStar.ValeSig\nmodule LSig = Vale.AsLowStar.LowStarSig\nmodule ME = Vale.X64.Memory\nmodule V = Vale.X64.Decls\nmodule IA = Vale.Interop.Assumptions\nmodule W = Vale.AsLowStar.Wrapper\nopen Vale.X64.MemoryAdapters\nmodule VS = Vale.X64.State\nmodule MS = Vale.X64.Machine_s\n\nlet lowstar_key128 : lowstar_key128_t =\n assert_norm (List.length dom + List.length ([]<:list arg) <= 4);\n IX64.wrap_weak_stdcall\n code_key128\n dom\n (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win))\n\nPartial implementation:\nlet aes128_key_expansion =\n \n"
},
{
"role": "assistant",
"content": "as_normal_t #lowstar_key128_t lowstar_key128"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Vale.Interop.Base.normal Vale.Stdcalls.X64.Aes.lowstar_key256_t\nEffect: Prims.Tot\n\nContext:\nmodule Vale.Stdcalls.X64.Aes\n\nopen FStar.Mul\nopen FStar.HyperStack.ST\nmodule HS = FStar.HyperStack\nmodule B = LowStar.Buffer\nmodule DV = LowStar.BufferView.Down\nmodule UV = LowStar.BufferView.Up\nopen Vale.Def.Types_s\n\nopen Vale.Interop.Base\nmodule IX64 = Vale.Interop.X64\nmodule VSig = Vale.AsLowStar.ValeSig\nmodule LSig = Vale.AsLowStar.LowStarSig\nmodule ME = Vale.X64.Memory\nmodule V = Vale.X64.Decls\nmodule IA = Vale.Interop.Assumptions\nmodule W = Vale.AsLowStar.Wrapper\nopen Vale.X64.MemoryAdapters\nmodule VS = Vale.X64.State\nmodule MS = Vale.X64.Machine_s\n\nlet lowstar_key128 : lowstar_key128_t =\n assert_norm (List.length dom + List.length ([]<:list arg) <= 4);\n IX64.wrap_weak_stdcall\n code_key128\n dom\n (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win))\n\nlet aes128_key_expansion //: normal lowstar_key128_t\n = as_normal_t #lowstar_key128_t lowstar_key128\n\nlet lowstar_key256 : lowstar_key256_t =\n assert_norm (List.length dom + List.length ([]<:list arg) <= 4);\n IX64.wrap_weak_stdcall\n code_key256\n dom\n (W.mk_prediction code_key256 dom [] (key256_lemma code_key256 IA.win))\n\nPartial implementation:\nlet aes256_key_expansion =\n \n"
},
{
"role": "assistant",
"content": "as_normal_t #lowstar_key256_t lowstar_key256"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: l1: IfcRulesReify.label -> l2: IfcRulesReify.label -> Prims.bool\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nPartial implementation:\nlet ( < ) l1 l2 =\n \n"
},
{
"role": "assistant",
"content": "match l1, l2 with\n| Low, High -> true\n| _, _ -> false"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: l1: IfcRulesReify.label -> l2: IfcRulesReify.label -> Prims.bool\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nPartial implementation:\nlet ( <= ) l1 l2 =\n \n"
},
{
"role": "assistant",
"content": "match l1, l2 with\n| High, Low -> false\n| _, _ -> true"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: env: IfcRulesReify.label_fun -> e: WhileReify.exp -> l: IfcRulesReify.label -> Type0\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n\nPartial implementation:\nlet ni_exp (env: label_fun) (e: exp) (l: label) : Tot Type0 =\n \n"
},
{
"role": "assistant",
"content": "forall (h: rel heap).\n (low_equiv env h /\\ Low? l) ==>\n (let vr = reify (interpret_exp_st e) (R?.r h) in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: l1: IfcRulesReify.label -> l2: IfcRulesReify.label -> IfcRulesReify.label\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nPartial implementation:\nlet join l1 l2 =\n \n"
},
{
"role": "assistant",
"content": "match l1, l2 with\n| Low, Low -> Low\n| _, _ -> High"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: l1: IfcRulesReify.label -> l2: IfcRulesReify.label -> IfcRulesReify.label\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nPartial implementation:\nlet meet l1 l2 =\n \n"
},
{
"role": "assistant",
"content": "match l1, l2 with\n| High, High -> High\n| _, _ -> Low"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n c: WhileReify.com ->\n l: IfcRulesReify.label ->\n h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap\n -> Type0\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nPartial implementation:\nlet ni_com' (env: label_fun) (c: com) (l: label) (h0: rel heap) : Tot Type0 =\n \n"
},
{
"role": "assistant",
"content": "let R h0l h0r = h0 in\nmatch interpret_com h0l c with\n| Some h1l ->\n (match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True)\n| _ -> True"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: env: IfcRulesReify.label_fun -> c: WhileReify.com -> l: IfcRulesReify.label -> Type0\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nPartial implementation:\nlet ni_com (env: label_fun) (c: com) (l: label) : Tot Type0 =\n \n"
},
{
"role": "assistant",
"content": "(forall (h0: rel heap). ni_com' env c l h0) /\\ (forall (h0: heap). inv_com' env c l h0)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n c: Pulse.Syntax.Base.comp_st ->\n frame: Pulse.Syntax.Base.term ->\n e: FStar.Stubs.Reflection.Types.term\n -> FStar.Stubs.Reflection.Types.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nPartial implementation:\nlet elab_frame (c: comp_st) (frame: term) (e: R.term) =\n \n"
},
{
"role": "assistant",
"content": "let u = comp_u c in\nlet ty = elab_term (comp_res c) in\nlet pre = elab_term (comp_pre c) in\nlet post = elab_term (comp_post c) in\nif C_ST? c\nthen mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\nelse\n if C_STAtomic? c\n then\n let opened = elab_term (comp_inames c) in\n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n bc: Pulse.Typing.bind_comp g x c1 c2 c ->\n e1: FStar.Stubs.Reflection.Types.term ->\n e2: FStar.Stubs.Reflection.Types.term\n -> FStar.Stubs.Reflection.Types.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\nPartial implementation:\nlet elab_bind #g #x #c1 #c2 #c (bc: bind_comp g x c1 c2 c) (e1: R.term) (e2: R.term) : R.term =\n \n"
},
{
"role": "assistant",
"content": "let t1 = elab_term (comp_res c1) in\nlet t2 = elab_term (comp_res c2) in\nmatch c1 with\n| C_ST _ ->\n mk_bind_stt (comp_u c1)\n (comp_u c2)\n t1\n t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1\n e2\n| C_STGhost _ ->\n mk_bind_ghost (comp_u c1)\n (comp_u c2)\n t1\n t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1\n e2\n| C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in\n mk_bind_atomic (comp_u c1) (comp_u c2) (elab_observability obs1) (elab_observability obs2)\n (elab_term (comp_inames c1)) t1 t2 (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2))) e1 e2"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: d: Pulse.Typing.lift_comp g c1 c2 -> e: FStar.Stubs.Reflection.Types.term\n -> FStar.Stubs.Reflection.Types.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\n\nlet elab_bind #g #x #c1 #c2 #c\n (bc:bind_comp g x c1 c2 c)\n (e1 e2:R.term)\n : R.term\n = let t1 = elab_term (comp_res c1) in\n let t2 = elab_term (comp_res c2) in\n match c1 with\n | C_ST _ ->\n mk_bind_stt\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STGhost _ ->\n mk_bind_ghost\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in \n mk_bind_atomic\n (comp_u c1)\n (comp_u c2)\n (elab_observability obs1)\n (elab_observability obs2)\n (elab_term (comp_inames c1))\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n\nPartial implementation:\nlet elab_lift #g #c1 #c2 (d: lift_comp g c1 c2) (e: R.term) : Tot R.term =\n \n"
},
{
"role": "assistant",
"content": "match d with\n| Lift_STAtomic_ST _ _ ->\n let t = elab_term (comp_res c1) in\n mk_lift_atomic_stt (comp_u c1)\n (elab_term (comp_res c1))\n t\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n| Lift_Observability _ c o2 ->\n let t = elab_term (comp_res c1) in\n mk_lift_observability (comp_u c1)\n (elab_observability (C_STAtomic?.obs c))\n (elab_observability o2)\n (elab_term (comp_inames c1))\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n| Lift_Ghost_Neutral _ _ (| reveal_a , reveal_a_typing |) ->\n let t = elab_term (comp_res c1) in\n mk_lift_ghost_neutral (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n (elab_term reveal_a)\n| Lift_Neutral_Ghost _ c ->\n let t = elab_term (comp_res c1) in\n mk_lift_neutral_ghost (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: t1: FStar.Stubs.Reflection.Types.term -> t2: FStar.Stubs.Reflection.Types.term\n -> FStar.Stubs.Reflection.Types.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\n\nlet elab_bind #g #x #c1 #c2 #c\n (bc:bind_comp g x c1 c2 c)\n (e1 e2:R.term)\n : R.term\n = let t1 = elab_term (comp_res c1) in\n let t2 = elab_term (comp_res c2) in\n match c1 with\n | C_ST _ ->\n mk_bind_stt\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STGhost _ ->\n mk_bind_ghost\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in \n mk_bind_atomic\n (comp_u c1)\n (comp_u c2)\n (elab_observability obs1)\n (elab_observability obs2)\n (elab_term (comp_inames c1))\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n \nlet elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term)\n : Tot R.term\n = match d with\n | Lift_STAtomic_ST _ _ ->\n let t = elab_term (comp_res c1) in\n mk_lift_atomic_stt\n (comp_u c1)\n (elab_term (comp_res c1))\n t\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\n | Lift_Observability _ c o2 ->\n let t = elab_term (comp_res c1) in\n mk_lift_observability\n (comp_u c1)\n (elab_observability (C_STAtomic?.obs c))\n (elab_observability o2)\n (elab_term (comp_inames c1))\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n \n | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) ->\n let t = elab_term (comp_res c1) in\n mk_lift_ghost_neutral\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n (elab_term reveal_a)\n\n | Lift_Neutral_Ghost _ c ->\n let t = elab_term (comp_res c1) in\n mk_lift_neutral_ghost\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\nlet intro_pure_tm (p:term) =\n let open Pulse.Reflection.Util in\n wtag (Some STT_Ghost) \n (Tm_STApp\n { head =\n tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid \"intro_pure\")))\n None\n p;\n arg_qual = None;\n arg = tm_fstar (`()) Range.range_0 })\n\nPartial implementation:\nlet simple_arr (t1 t2: R.term) : R.term =\n \n"
},
{
"role": "assistant",
"content": "let b = R.pack_binder ({ sort = t1; ppname = Sealed.seal \"x\"; qual = R.Q_Explicit; attrs = [] }) in\nR.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Vale.Stdcalls.X64.Aes.lowstar_key128_t\nEffect: Prims.Tot\n\nContext:\nmodule Vale.Stdcalls.X64.Aes\n\nopen FStar.Mul\nopen FStar.HyperStack.ST\nmodule HS = FStar.HyperStack\nmodule B = LowStar.Buffer\nmodule DV = LowStar.BufferView.Down\nmodule UV = LowStar.BufferView.Up\nopen Vale.Def.Types_s\n\nopen Vale.Interop.Base\nmodule IX64 = Vale.Interop.X64\nmodule VSig = Vale.AsLowStar.ValeSig\nmodule LSig = Vale.AsLowStar.LowStarSig\nmodule ME = Vale.X64.Memory\nmodule V = Vale.X64.Decls\nmodule IA = Vale.Interop.Assumptions\nmodule W = Vale.AsLowStar.Wrapper\nopen Vale.X64.MemoryAdapters\nmodule VS = Vale.X64.State\nmodule MS = Vale.X64.Machine_s\n\nPartial implementation:\nlet lowstar_key128:lowstar_key128_t =\n \n"
},
{
"role": "assistant",
"content": "assert_norm (List.length dom + List.length ([] <: list arg) <= 4);\nIX64.wrap_weak_stdcall code_key128\n dom\n (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n c1: Pulse.Syntax.Base.comp_st ->\n c2: Pulse.Syntax.Base.comp_st ->\n e: FStar.Stubs.Reflection.Types.term\n -> FStar.Stubs.Reflection.Types.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nPartial implementation:\nlet elab_sub (c1 c2: comp_st) (e: R.term) =\n \n"
},
{
"role": "assistant",
"content": "let ty = elab_term (comp_res c1) in\nlet u = comp_u c1 in\nlet pre1 = elab_term (comp_pre c1) in\nlet pre2 = elab_term (comp_pre c2) in\nlet post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\nlet post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\nif C_ST? c1\nthen mk_sub_stt u ty pre1 pre2 post1 post2 e\nelse\n if C_STAtomic? c1\n then\n let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n c: WhileReify.com ->\n l: IfcRulesReify.label ->\n h0: FStar.DM4F.Heap.IntStoreFixed.heap\n -> Type0\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n\nPartial implementation:\nlet inv_com' (env: label_fun) (c: com) (l: label) (h0: heap) : Tot Type0 =\n \n"
},
{
"role": "assistant",
"content": "match interpret_com h0 c with\n| None -> True\n| Some h1 -> forall (i: id). env i < l ==> index h0 i = index h1 i"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: p: Pulse.Syntax.Base.term -> Pulse.Syntax.Base.st_term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\n\nlet elab_bind #g #x #c1 #c2 #c\n (bc:bind_comp g x c1 c2 c)\n (e1 e2:R.term)\n : R.term\n = let t1 = elab_term (comp_res c1) in\n let t2 = elab_term (comp_res c2) in\n match c1 with\n | C_ST _ ->\n mk_bind_stt\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STGhost _ ->\n mk_bind_ghost\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in \n mk_bind_atomic\n (comp_u c1)\n (comp_u c2)\n (elab_observability obs1)\n (elab_observability obs2)\n (elab_term (comp_inames c1))\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n \nlet elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term)\n : Tot R.term\n = match d with\n | Lift_STAtomic_ST _ _ ->\n let t = elab_term (comp_res c1) in\n mk_lift_atomic_stt\n (comp_u c1)\n (elab_term (comp_res c1))\n t\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\n | Lift_Observability _ c o2 ->\n let t = elab_term (comp_res c1) in\n mk_lift_observability\n (comp_u c1)\n (elab_observability (C_STAtomic?.obs c))\n (elab_observability o2)\n (elab_term (comp_inames c1))\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n \n | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) ->\n let t = elab_term (comp_res c1) in\n mk_lift_ghost_neutral\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n (elab_term reveal_a)\n\n | Lift_Neutral_Ghost _ c ->\n let t = elab_term (comp_res c1) in\n mk_lift_neutral_ghost\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\nPartial implementation:\nlet intro_pure_tm (p: term) =\n \n"
},
{
"role": "assistant",
"content": "let open Pulse.Reflection.Util in\nwtag (Some STT_Ghost)\n (Tm_STApp\n ({\n head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid \"intro_pure\"))) None p;\n arg_qual = None;\n arg = tm_fstar (`()) Range.range_0\n }))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n r: FStar.DM4F.Heap.IntStoreFixed.id ->\n h0: FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma (ensures IfcRulesReify.inv_com' env (WhileReify.Assign r e) (env r) h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nPartial implementation:\nlet assign_inv_com' (env: label_fun) (e: exp) (r: id) (h0: heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0) =\n \n"
},
{
"role": "assistant",
"content": "let v = reify (interpret_exp_st e) h0 in\nmatch reify (interpret_com_st (Assign r e) h0) h0 with\n| None, h1 -> ()\n| Some (), h1 -> assert (h1 == upd h0 r v)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: env: IfcRulesReify.label_fun -> e: WhileReify.exp -> r: FStar.DM4F.Heap.IntStoreFixed.id\n -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e (env r))\n (ensures IfcRulesReify.ni_com env (WhileReify.Assign r e) (env r))\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n\nPartial implementation:\nlet assign_com env e r =\n \n"
},
{
"role": "assistant",
"content": "forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r))));\nforall_intro (assign_inv_com' env e r)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n r: FStar.DM4F.Heap.IntStoreFixed.id ->\n ne: Prims.squash (IfcRulesReify.ni_exp env e (env r)) ->\n h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma (ensures IfcRulesReify.ni_com' env (WhileReify.Assign r e) (env r) h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nPartial implementation:\nlet assign_inv_com0\n (env: label_fun)\n (e: exp)\n (r: id)\n (ne: squash (ni_exp env e (env r)))\n (h0: rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0) =\n \n"
},
{
"role": "assistant",
"content": "FStar.Squash.give_proof ne;\nlet vr = reify (interpret_exp_st e) (R?.r h0) in\nlet vl = reify (interpret_exp_st e) (R?.l h0) in\nmatch reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n| Some (), h1l ->\n (match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ())\n| None, _ -> ()"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Vale.Stdcalls.X64.Aes.lowstar_key256_t\nEffect: Prims.Tot\n\nContext:\nmodule Vale.Stdcalls.X64.Aes\n\nopen FStar.Mul\nopen FStar.HyperStack.ST\nmodule HS = FStar.HyperStack\nmodule B = LowStar.Buffer\nmodule DV = LowStar.BufferView.Down\nmodule UV = LowStar.BufferView.Up\nopen Vale.Def.Types_s\n\nopen Vale.Interop.Base\nmodule IX64 = Vale.Interop.X64\nmodule VSig = Vale.AsLowStar.ValeSig\nmodule LSig = Vale.AsLowStar.LowStarSig\nmodule ME = Vale.X64.Memory\nmodule V = Vale.X64.Decls\nmodule IA = Vale.Interop.Assumptions\nmodule W = Vale.AsLowStar.Wrapper\nopen Vale.X64.MemoryAdapters\nmodule VS = Vale.X64.State\nmodule MS = Vale.X64.Machine_s\n\nlet lowstar_key128 : lowstar_key128_t =\n assert_norm (List.length dom + List.length ([]<:list arg) <= 4);\n IX64.wrap_weak_stdcall\n code_key128\n dom\n (W.mk_prediction code_key128 dom [] (key128_lemma code_key128 IA.win))\n\nlet aes128_key_expansion //: normal lowstar_key128_t\n = as_normal_t #lowstar_key128_t lowstar_key128\n\nPartial implementation:\nlet lowstar_key256:lowstar_key256_t =\n \n"
},
{
"role": "assistant",
"content": "assert_norm (List.length dom + List.length ([] <: list arg) <= 4);\nIX64.wrap_weak_stdcall code_key256\n dom\n (W.mk_prediction code_key256 dom [] (key256_lemma code_key256 IA.win))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: env: IfcRulesReify.label_fun -> c1: WhileReify.com -> c2: WhileReify.com -> l: IfcRulesReify.label\n -> FStar.Pervasives.Lemma\n (requires IfcRulesReify.ni_com env c1 l /\\ IfcRulesReify.ni_com env c2 l)\n (ensures IfcRulesReify.ni_com env (WhileReify.Seq c1 c2) l)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n\nPartial implementation:\nlet seq_com env c1 c2 l =\n \n"
},
{
"role": "assistant",
"content": "forall_intro (fun (h0: rel heap) -> seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0));\nforall_intro (fun (h0: heap) -> seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0)\n )"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n c1: WhileReify.com ->\n c2: WhileReify.com ->\n l: IfcRulesReify.label ->\n h0: FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma\n (requires IfcRulesReify.ni_com env c1 l /\\ IfcRulesReify.ni_com env c2 l)\n (ensures IfcRulesReify.inv_com' env (WhileReify.Seq c1 c2) l h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n\nPartial implementation:\nlet seq_inv_com' env c1 c2 l h0 =\n \n"
},
{
"role": "assistant",
"content": "match reify (interpret_com_st c1 h0) h0 with\n| None, _ -> seq_nil1 c1 c2 h0\n| Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n ct: WhileReify.com ->\n cf: WhileReify.com ->\n l: IfcRulesReify.label ->\n h0: FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma\n (requires\n IfcRulesReify.ni_exp env e l /\\ IfcRulesReify.ni_com env ct l /\\\n IfcRulesReify.ni_com env cf l)\n (ensures IfcRulesReify.inv_com' env (WhileReify.If e ct cf) l h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com env (Seq c1 c2) l))\nlet seq_com env c1 c2 l =\n forall_intro\n (fun (h0:rel heap) ->\n seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))\n\n(* Typing rule for conditional commands\n\n env |- e : l env,pc:l |- ct env,pc:l |- cf\n ----------------------------------------------\n env,pc:l |- if e <> 0 then ct else cf\n*)\n\n(* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *)\n\nval cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n\nPartial implementation:\nlet cond_inv_com' env e ct cf l h0 =\n \n"
},
{
"role": "assistant",
"content": "let v = reify (interpret_exp_st e) h0 in\nif v = 0\nthen assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0)\nelse assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n g: Pulse.Typing.Env.env ->\n pre: Pulse.Syntax.Base.term ->\n pre_typing: Pulse.Typing.tot_typing g pre Pulse.Syntax.Base.tm_vprop ->\n post_hint: Pulse.Typing.post_hint_opt g ->\n res_ppname: Pulse.Syntax.Base.ppname ->\n t: Pulse.Syntax.Base.st_term{Tm_IntroPure? (Mkst_term?.term t)}\n -> FStar.Tactics.Effect.Tac (Pulse.Checker.Base.checker_result_t g pre post_hint)\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Checker.IntroPure\n\nopen Pulse.Syntax\nopen Pulse.Typing\nopen Pulse.Checker.Base\nopen Pulse.Checker.Prover\n\nmodule T = FStar.Tactics.V2\nmodule P = Pulse.Syntax.Printer\n\nlet check_prop (g:env) (p:term) \n : T.Tac (p:term & tot_typing g p tm_prop) =\n \n let p0 = p in\n let (| p, p_typing |) = Pulse.Checker.Pure.check_vprop g (tm_pure p) in\n match p.t with\n | Tm_Pure pp ->\n let prop_typing = Pulse.Typing.Metatheory.pure_typing_inversion #_ #pp p_typing in\n (| pp, prop_typing |)\n | _ ->\n fail g None\n (Printf.sprintf \"Impossible: check_intro_pure: checking a pure vprop %s returned a non-pure vprop %s,\\\n please file a bug-report\"\n (P.term_to_string (tm_pure p0))\n (P.term_to_string p))\n\nlet check_prop_validity (g:env) (p:term) (typing:tot_typing g p tm_prop): T.Tac (prop_validity g p) =\n Pulse.Checker.Pure.check_prop_validity g p typing\n\nPartial implementation:\nlet check\n (g: env)\n (pre: term)\n (pre_typing: tot_typing g pre tm_vprop)\n (post_hint: post_hint_opt g)\n (res_ppname: ppname)\n (t: st_term{Tm_IntroPure? t.term})\n : T.Tac (checker_result_t g pre post_hint) =\n \n"
},
{
"role": "assistant",
"content": "let g = Pulse.Typing.Env.push_context g \"check_intro_pure\" t.range in\nlet Tm_IntroPure { p = p } = t.term in\nlet (| p , p_typing |) = check_prop g p in\nlet pv = check_prop_validity g p p_typing in\nlet st_typing = T_IntroPure _ _ p_typing pv in\nprove_post_hint (try_frame_pre pre_typing\n (match_comp_res_with_post_hint st_typing post_hint)\n res_ppname)\n post_hint\n t.range"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n st: Hacl.Spec.SHA2.Vec.state_spec a m ->\n j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} ->\n i: Prims.nat{i < 8 * Spec.Hash.Definitions.word_length a}\n -> FStar.Pervasives.Lemma\n (ensures\n (let l = Hacl.Spec.SHA2.Vec.lanes a m in\n let ind = 8 * j + i / Spec.Hash.Definitions.word_length a in\n FStar.Seq.Base.index (Lib.IntVector.vec_v (Hacl.Spec.SHA2.Vec.transpose_state st).[ ind / l\n ])\n (ind % l) ==\n FStar.Seq.Base.index (Hacl.Spec.SHA2.Vec.state_spec_v st).[ j ]\n (i / Spec.Hash.Definitions.word_length a)))\nEffect: FStar.Pervasives.Lemma\n\nContext:\nmodule Hacl.Spec.SHA2.Lemmas\n\nopen FStar.Mul\nopen Lib.IntTypes\nopen Lib.Sequence\nopen Lib.IntVector\nopen Lib.IntVector.Transpose\n\nopen Spec.Hash.Definitions\nopen Hacl.Spec.SHA2.Vec\n\n\n#set-options \"--z3rlimit 50 --fuel 0 --ifuel 1\"\n\nval transpose_ws4_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws4_lemma_ij #a #m ws j i =\n let l = lanes a m in\n let i_sub = i / l in\n let j_sub = i % l in\n assert (i_sub * l + j_sub == i);\n\n let vs = sub ws (i_sub * l) l in\n eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs);\n //assert ((transpose_ws4 ws).[i] == (sub (transpose_ws4 ws) (i_sub * l) l).[j_sub]);\n //assert ((transpose_ws4 ws).[i] == (transpose4x4_lseq vs).[j_sub]);\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v (transpose4x4_lseq vs).[j_sub]).[j]);\n transpose4x4_lemma vs;\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v vs.[j]).[j_sub]);\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i_sub * l + j]).[j_sub])\n\n\nval transpose_ws8_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 8}\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n (vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws8_lemma_ij #a #m ws j i =\n let l = lanes a m in\n let i_sub = i / l in\n let j_sub = i % l in\n assert (i_sub * l + j_sub == i);\n\n let vs = sub ws (i_sub * l) l in\n eq_intro (sub (transpose_ws8 ws) (i_sub * l) l) (transpose8x8_lseq vs);\n assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v (transpose8x8_lseq vs).[j_sub]).[j]);\n transpose8x8_lemma vs;\n assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i_sub * lanes a m + j]).[j_sub])\n\n\nval transpose_ws_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{is_supported a m}\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws_lemma_ij #a #m ws j i =\n assert (((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v (transpose_ws ws).[i]).[j]);\n match lanes a m with\n | 1 -> ()\n | 4 -> transpose_ws4_lemma_ij #a #m ws j i\n | 8 -> transpose_ws8_lemma_ij #a #m ws j i\n\n\nval transpose_state4_lemma:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 4}\n -> st:state_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 8 * word_length a} ->\n Lemma\n (let l = lanes a m in\n let ind = 8 * j + i / word_length a in\n Seq.index (vec_v (transpose_state st).[ind / l]) (ind % l) ==\n Seq.index (state_spec_v st).[j] (i / word_length a))\n\nlet transpose_state4_lemma #a #m st j i =\n let r0 = transpose4x4_lseq (sub st 0 4) in\n transpose4x4_lemma (sub st 0 4);\n let r1 = transpose4x4_lseq (sub st 4 4) in\n transpose4x4_lemma (sub st 4 4)\n\n\nval transpose_state8_lemma:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 8}\n -> st:state_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 8 * word_length a} ->\n Lemma\n (let l = lanes a m in\n let ind = 8 * j + i / word_length a in\n Seq.index (vec_v (transpose_state8 st).[ind / l]) (ind % l) ==\n Seq.index (state_spec_v st).[j] (i / word_length a))\n\nlet transpose_state8_lemma #a #m st j i =\n let l = lanes a m in\n let ind = 8 * j + i / word_length a in\n let r0 = transpose8x8_lseq st in\n transpose8x8_lemma st\n\n\nval transpose_state_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{is_supported a m}\n -> st:state_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 8 * word_length a} ->\n Lemma\n (let l = lanes a m in\n let ind = 8 * j + i / word_length a in\n (Seq.index (vec_v (transpose_state st).[ind / l])) (ind % l) ==\n (Seq.index (state_spec_v st).[j] (i / word_length a)))\n\nPartial implementation:\nlet transpose_state_lemma_ij #a #m st j i =\n \n"
},
{
"role": "assistant",
"content": "match lanes a m with\n| 1 -> ()\n| 4 -> transpose_state4_lemma #a #m st j i\n| 8 -> transpose_state8_lemma #a #m st j i"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n ct: WhileReify.com ->\n cf: WhileReify.com ->\n l: IfcRulesReify.label\n -> FStar.Pervasives.Lemma\n (requires\n IfcRulesReify.ni_exp env e l /\\ IfcRulesReify.ni_com env ct l /\\\n IfcRulesReify.ni_com env cf l) (ensures IfcRulesReify.ni_com env (WhileReify.If e ct cf) l)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com env (Seq c1 c2) l))\nlet seq_com env c1 c2 l =\n forall_intro\n (fun (h0:rel heap) ->\n seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))\n\n(* Typing rule for conditional commands\n\n env |- e : l env,pc:l |- ct env,pc:l |- cf\n ----------------------------------------------\n env,pc:l |- if e <> 0 then ct else cf\n*)\n\n(* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *)\n\nval cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (inv_com' env (If e ct cf) l h0))\nlet cond_inv_com' env e ct cf l h0 =\n let v = reify (interpret_exp_st e) h0 in\n if v = 0\n then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0)\n else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)\n\n (* Works too but takes 20s more *)\n (* let c = if v = 0 then cf else ct in *)\n (* match reify (interpret_com_st c h0) h0 with *)\n (* | None, _ -> () *)\n (* | Some (), h1 -> () *)\n#reset-options \"--max_fuel 1\"\nlet interpret_cond (e:exp) (ct:com) (cf:com) (h:heap)\n : Lemma (let v = reify (interpret_exp_st e) h in\n let c = if v = 0 then cf else ct in\n (reify (interpret_com_st (If e ct cf) h) h ==\n reify (interpret_com_st c h) h))\n = ()\n\n\nval cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com' env (If e ct cf) l h0))\nlet cond_ni_com' env e ct cf l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else\n let R h0l h0r = h0 in\n let vl = reify (interpret_exp_st e) h0l in\n let vr = reify (interpret_exp_st e) h0r in\n if Low? l\n then begin\n assert (vl == vr) ;\n let c = if vl = 0 then cf else ct in\n assert (ni_com env c l) ;\n let cif = If e ct cf in\n //NS:05/15 ... this 2 should be trivial to prove.\n // Why do they require a lemma?\n interpret_cond e ct cf h0l;\n interpret_cond e ct cf h0r;\n use_ni_com env c l (R h0l h0r)\n end\n else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n match reify (interpret_com_st (If e ct cf) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (If e ct cf) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n cond_inv_com' env e ct cf l h0l ;\n cond_inv_com' env e ct cf l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\n#set-options \"--z3rlimit 5\"\n\nval cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n\nPartial implementation:\nlet cond_com env e ct cf l =\n \n"
},
{
"role": "assistant",
"content": "forall_intro (fun (h0: rel heap) ->\n cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0));\nforall_intro (fun (h0: heap) ->\n cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n c: WhileReify.com ->\n v: WhileReify.metric ->\n l: IfcRulesReify.label\n -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\\ IfcRulesReify.ni_com env c l)\n (ensures IfcRulesReify.ni_com env (WhileReify.While e c v) l)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com env (Seq c1 c2) l))\nlet seq_com env c1 c2 l =\n forall_intro\n (fun (h0:rel heap) ->\n seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))\n\n(* Typing rule for conditional commands\n\n env |- e : l env,pc:l |- ct env,pc:l |- cf\n ----------------------------------------------\n env,pc:l |- if e <> 0 then ct else cf\n*)\n\n(* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *)\n\nval cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (inv_com' env (If e ct cf) l h0))\nlet cond_inv_com' env e ct cf l h0 =\n let v = reify (interpret_exp_st e) h0 in\n if v = 0\n then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0)\n else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)\n\n (* Works too but takes 20s more *)\n (* let c = if v = 0 then cf else ct in *)\n (* match reify (interpret_com_st c h0) h0 with *)\n (* | None, _ -> () *)\n (* | Some (), h1 -> () *)\n#reset-options \"--max_fuel 1\"\nlet interpret_cond (e:exp) (ct:com) (cf:com) (h:heap)\n : Lemma (let v = reify (interpret_exp_st e) h in\n let c = if v = 0 then cf else ct in\n (reify (interpret_com_st (If e ct cf) h) h ==\n reify (interpret_com_st c h) h))\n = ()\n\n\nval cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com' env (If e ct cf) l h0))\nlet cond_ni_com' env e ct cf l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else\n let R h0l h0r = h0 in\n let vl = reify (interpret_exp_st e) h0l in\n let vr = reify (interpret_exp_st e) h0r in\n if Low? l\n then begin\n assert (vl == vr) ;\n let c = if vl = 0 then cf else ct in\n assert (ni_com env c l) ;\n let cif = If e ct cf in\n //NS:05/15 ... this 2 should be trivial to prove.\n // Why do they require a lemma?\n interpret_cond e ct cf h0l;\n interpret_cond e ct cf h0r;\n use_ni_com env c l (R h0l h0r)\n end\n else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n match reify (interpret_com_st (If e ct cf) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (If e ct cf) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n cond_inv_com' env e ct cf l h0l ;\n cond_inv_com' env e ct cf l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\n#set-options \"--z3rlimit 5\"\n\nval cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com env (If e ct cf) l))\nlet cond_com env e ct cf l =\n forall_intro\n (fun (h0:rel heap) ->\n cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0))\n\n\n(* Typing rule for Skip\n\n -------------------\n env,pc:High |- skip\n*)\n\nval skip_com : env:label_fun ->\n Lemma (ni_com env Skip High)\nlet skip_com _ = ()\n\n(* While rule for commands\n\n env |- e : l env,pc:l |- c\n -----------------------------------\n env,pc:l |- while (e <> 0) do c\n*)\n\n\nval while_inv_com'\n : env:label_fun ->\n e:exp ->\n c:com ->\n v:metric ->\n l:label ->\n h0:heap ->\n Lemma\n (requires (ni_exp env e l /\\ ni_com env c l))\n (ensures (inv_com' env (While e c v) l h0))\n (decreases (decr_while h0 (While e c v)))\n\n#reset-options \"--z3rlimit 40\"\n\nlet interpret_while_nil e c v h\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n fst (reify (interpret_com_st c h) h) == None))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap)\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n (match reify (interpret_com_st c h) h with\n | None, _ -> True\n | Some _, h' ->\n interpret_exp' h' v >= interpret_exp' h v)))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet rec while_inv_com' env e c v l h0 =\n let v0 = reify (interpret_exp_st e) h0 in\n if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0)\n else\n let m0 = interpret_exp' h0 v in\n match reify (interpret_com_st c h0) h0 with\n | None, _ -> interpret_while_nil e c v h0\n | Some (), h2 ->\n let m1 = interpret_exp' h2 v in\n if m0 > m1\n then begin\n assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ;\n while_inv_com' env e c v l h2\n end\n else interpret_while_loops e c v h0\n\nval while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l /\\ low_equiv env h0 /\\ High? l))\n (ensures (ni_com' env (While e c v) l h0))\nlet while_ni_com'_low_equiv_high env e c v l h0 =\n (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n let R h0l h0r = h0 in\n match reify (interpret_com_st (While e c v) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (While e c v) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n while_inv_com' env e c v l h0l ;\n while_inv_com' env e c v l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\nval while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l /\\ low_equiv env h0 /\\ Low? l))\n (ensures (ni_com' env (While e c v) l h0))\n (decreases (decr_while (R?.l h0) (While e c v) + decr_while (R?.r h0) (While e c v)))\nlet rec while_ni_com'_low_equiv_low env e c v l h0 =\n let R h0l h0r = h0 in\n let v0l = reify (interpret_exp_st e) h0l in\n let v0r = reify (interpret_exp_st e) h0r in\n assert (v0l == v0r) ;\n if v0l = 0 then begin\n assert (interpret_com h0l (While e c v) == Some h0l);\n assert (interpret_com h0r (While e c v) == Some h0r)\n end\n else\n let m0l = interpret_exp' h0l v in\n let m0r = interpret_exp' h0r v in\n match reify (interpret_com_st c h0l) h0l with\n | None, _ -> interpret_while_nil e c v h0l\n | Some (), h2l ->\n match reify (interpret_com_st c h0r) h0r with\n | None, _ -> interpret_while_nil e c v h0r\n | Some (), h2r ->\n let m1l = interpret_exp' h2l v in\n let m1r = interpret_exp' h2r v in\n if m0l > m1l\n then if m0r > m1r\n then begin\n assert (decr_while h2l (While e c v) << decr_while h0l (While e c v)) ;\n while_ni_com'_low_equiv_low env e c v l (R h2l h2r)\n end\n else interpret_while_loops e c v h0r\n else interpret_while_loops e c v h0l\n\nval while_ni_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l))\n (ensures (ni_com' env (While e c v) l h0))\n#set-options \"--max_fuel 1 --max_ifuel 1 --z3rlimit 50\"\nlet while_ni_com' env e c v l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else if Low? l\n then while_ni_com'_low_equiv_low env e c v l h0\n else while_ni_com'_low_equiv_high env e c v l h0\n\n#set-options \"--z3rlimit 5\"\n\nval while_com : env:label_fun -> e:exp -> c:com -> v:metric -> l:label ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l))\n\nPartial implementation:\nlet while_com env e c v l =\n \n"
},
{
"role": "assistant",
"content": "forall_intro (fun (h: rel heap) ->\n while_ni_com' env e c v l h <: Lemma (ensures (ni_com' env (While e c v) l h)));\nforall_intro (fun (h0: heap) ->\n while_inv_com' env e c v l h0 <: Lemma (ensures (inv_com' env (While e c v) l h0)))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n ct: WhileReify.com ->\n cf: WhileReify.com ->\n l: IfcRulesReify.label ->\n h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma\n (requires\n IfcRulesReify.ni_exp env e l /\\ IfcRulesReify.ni_com env ct l /\\\n IfcRulesReify.ni_com env cf l)\n (ensures IfcRulesReify.ni_com' env (WhileReify.If e ct cf) l h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com env (Seq c1 c2) l))\nlet seq_com env c1 c2 l =\n forall_intro\n (fun (h0:rel heap) ->\n seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))\n\n(* Typing rule for conditional commands\n\n env |- e : l env,pc:l |- ct env,pc:l |- cf\n ----------------------------------------------\n env,pc:l |- if e <> 0 then ct else cf\n*)\n\n(* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *)\n\nval cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (inv_com' env (If e ct cf) l h0))\nlet cond_inv_com' env e ct cf l h0 =\n let v = reify (interpret_exp_st e) h0 in\n if v = 0\n then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0)\n else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)\n\n (* Works too but takes 20s more *)\n (* let c = if v = 0 then cf else ct in *)\n (* match reify (interpret_com_st c h0) h0 with *)\n (* | None, _ -> () *)\n (* | Some (), h1 -> () *)\n#reset-options \"--max_fuel 1\"\nlet interpret_cond (e:exp) (ct:com) (cf:com) (h:heap)\n : Lemma (let v = reify (interpret_exp_st e) h in\n let c = if v = 0 then cf else ct in\n (reify (interpret_com_st (If e ct cf) h) h ==\n reify (interpret_com_st c h) h))\n = ()\n\n\nval cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n\nPartial implementation:\nlet cond_ni_com' env e ct cf l h0 =\n \n"
},
{
"role": "assistant",
"content": "if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\nthen ()\nelse\n let R h0l h0r = h0 in\n let vl = reify (interpret_exp_st e) h0l in\n let vr = reify (interpret_exp_st e) h0r in\n if Low? l\n then\n (assert (vl == vr);\n let c = if vl = 0 then cf else ct in\n assert (ni_com env c l);\n let cif = If e ct cf in\n interpret_cond e ct cf h0l;\n interpret_cond e ct cf h0r;\n use_ni_com env c l (R h0l h0r))\n else\n match reify (interpret_com_st (If e ct cf) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (If e ct cf) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n cond_inv_com' env e ct cf l h0l;\n cond_inv_com' env e ct cf l h0r;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n c1: WhileReify.com ->\n c2: WhileReify.com ->\n l: IfcRulesReify.label ->\n h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma\n (requires IfcRulesReify.ni_com env c1 l /\\ IfcRulesReify.ni_com env c2 l)\n (ensures IfcRulesReify.ni_com' env (WhileReify.Seq c1 c2) l h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n\nPartial implementation:\nlet seq_com' env c1 c2 l h0 =\n \n"
},
{
"role": "assistant",
"content": "if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\nthen ()\nelse\n (assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1);\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n c: WhileReify.com ->\n v: WhileReify.metric ->\n l: IfcRulesReify.label ->\n h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma (requires IfcRulesReify.ni_exp env e l /\\ IfcRulesReify.ni_com env c l)\n (ensures IfcRulesReify.ni_com' env (WhileReify.While e c v) l h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com env (Seq c1 c2) l))\nlet seq_com env c1 c2 l =\n forall_intro\n (fun (h0:rel heap) ->\n seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))\n\n(* Typing rule for conditional commands\n\n env |- e : l env,pc:l |- ct env,pc:l |- cf\n ----------------------------------------------\n env,pc:l |- if e <> 0 then ct else cf\n*)\n\n(* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *)\n\nval cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (inv_com' env (If e ct cf) l h0))\nlet cond_inv_com' env e ct cf l h0 =\n let v = reify (interpret_exp_st e) h0 in\n if v = 0\n then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0)\n else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)\n\n (* Works too but takes 20s more *)\n (* let c = if v = 0 then cf else ct in *)\n (* match reify (interpret_com_st c h0) h0 with *)\n (* | None, _ -> () *)\n (* | Some (), h1 -> () *)\n#reset-options \"--max_fuel 1\"\nlet interpret_cond (e:exp) (ct:com) (cf:com) (h:heap)\n : Lemma (let v = reify (interpret_exp_st e) h in\n let c = if v = 0 then cf else ct in\n (reify (interpret_com_st (If e ct cf) h) h ==\n reify (interpret_com_st c h) h))\n = ()\n\n\nval cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com' env (If e ct cf) l h0))\nlet cond_ni_com' env e ct cf l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else\n let R h0l h0r = h0 in\n let vl = reify (interpret_exp_st e) h0l in\n let vr = reify (interpret_exp_st e) h0r in\n if Low? l\n then begin\n assert (vl == vr) ;\n let c = if vl = 0 then cf else ct in\n assert (ni_com env c l) ;\n let cif = If e ct cf in\n //NS:05/15 ... this 2 should be trivial to prove.\n // Why do they require a lemma?\n interpret_cond e ct cf h0l;\n interpret_cond e ct cf h0r;\n use_ni_com env c l (R h0l h0r)\n end\n else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n match reify (interpret_com_st (If e ct cf) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (If e ct cf) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n cond_inv_com' env e ct cf l h0l ;\n cond_inv_com' env e ct cf l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\n#set-options \"--z3rlimit 5\"\n\nval cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com env (If e ct cf) l))\nlet cond_com env e ct cf l =\n forall_intro\n (fun (h0:rel heap) ->\n cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0))\n\n\n(* Typing rule for Skip\n\n -------------------\n env,pc:High |- skip\n*)\n\nval skip_com : env:label_fun ->\n Lemma (ni_com env Skip High)\nlet skip_com _ = ()\n\n(* While rule for commands\n\n env |- e : l env,pc:l |- c\n -----------------------------------\n env,pc:l |- while (e <> 0) do c\n*)\n\n\nval while_inv_com'\n : env:label_fun ->\n e:exp ->\n c:com ->\n v:metric ->\n l:label ->\n h0:heap ->\n Lemma\n (requires (ni_exp env e l /\\ ni_com env c l))\n (ensures (inv_com' env (While e c v) l h0))\n (decreases (decr_while h0 (While e c v)))\n\n#reset-options \"--z3rlimit 40\"\n\nlet interpret_while_nil e c v h\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n fst (reify (interpret_com_st c h) h) == None))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap)\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n (match reify (interpret_com_st c h) h with\n | None, _ -> True\n | Some _, h' ->\n interpret_exp' h' v >= interpret_exp' h v)))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet rec while_inv_com' env e c v l h0 =\n let v0 = reify (interpret_exp_st e) h0 in\n if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0)\n else\n let m0 = interpret_exp' h0 v in\n match reify (interpret_com_st c h0) h0 with\n | None, _ -> interpret_while_nil e c v h0\n | Some (), h2 ->\n let m1 = interpret_exp' h2 v in\n if m0 > m1\n then begin\n assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ;\n while_inv_com' env e c v l h2\n end\n else interpret_while_loops e c v h0\n\nval while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l /\\ low_equiv env h0 /\\ High? l))\n (ensures (ni_com' env (While e c v) l h0))\nlet while_ni_com'_low_equiv_high env e c v l h0 =\n (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n let R h0l h0r = h0 in\n match reify (interpret_com_st (While e c v) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (While e c v) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n while_inv_com' env e c v l h0l ;\n while_inv_com' env e c v l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\nval while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l /\\ low_equiv env h0 /\\ Low? l))\n (ensures (ni_com' env (While e c v) l h0))\n (decreases (decr_while (R?.l h0) (While e c v) + decr_while (R?.r h0) (While e c v)))\nlet rec while_ni_com'_low_equiv_low env e c v l h0 =\n let R h0l h0r = h0 in\n let v0l = reify (interpret_exp_st e) h0l in\n let v0r = reify (interpret_exp_st e) h0r in\n assert (v0l == v0r) ;\n if v0l = 0 then begin\n assert (interpret_com h0l (While e c v) == Some h0l);\n assert (interpret_com h0r (While e c v) == Some h0r)\n end\n else\n let m0l = interpret_exp' h0l v in\n let m0r = interpret_exp' h0r v in\n match reify (interpret_com_st c h0l) h0l with\n | None, _ -> interpret_while_nil e c v h0l\n | Some (), h2l ->\n match reify (interpret_com_st c h0r) h0r with\n | None, _ -> interpret_while_nil e c v h0r\n | Some (), h2r ->\n let m1l = interpret_exp' h2l v in\n let m1r = interpret_exp' h2r v in\n if m0l > m1l\n then if m0r > m1r\n then begin\n assert (decr_while h2l (While e c v) << decr_while h0l (While e c v)) ;\n while_ni_com'_low_equiv_low env e c v l (R h2l h2r)\n end\n else interpret_while_loops e c v h0r\n else interpret_while_loops e c v h0l\n\nval while_ni_com' : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l))\n (ensures (ni_com' env (While e c v) l h0))\n\nPartial implementation:\nlet while_ni_com' env e c v l h0 =\n \n"
},
{
"role": "assistant",
"content": "if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\nthen ()\nelse\n if Low? l\n then while_ni_com'_low_equiv_low env e c v l h0\n else while_ni_com'_low_equiv_high env e c v l h0"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: h: FStar.Tactics.NamedView.binding -> FStar.Tactics.Effect.Tac Prims.unit\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nPartial implementation:\nlet and_elim' (h: binding) : Tac unit =\n \n"
},
{
"role": "assistant",
"content": "and_elim (pack (Tv_Var h));\nclear h"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n c: WhileReify.com ->\n v: WhileReify.metric ->\n l: IfcRulesReify.label ->\n h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma\n (requires\n IfcRulesReify.ni_exp env e l /\\ IfcRulesReify.ni_com env c l /\\\n IfcRulesReify.low_equiv env h0 /\\ High? l)\n (ensures IfcRulesReify.ni_com' env (WhileReify.While e c v) l h0)\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com env (Seq c1 c2) l))\nlet seq_com env c1 c2 l =\n forall_intro\n (fun (h0:rel heap) ->\n seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))\n\n(* Typing rule for conditional commands\n\n env |- e : l env,pc:l |- ct env,pc:l |- cf\n ----------------------------------------------\n env,pc:l |- if e <> 0 then ct else cf\n*)\n\n(* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *)\n\nval cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (inv_com' env (If e ct cf) l h0))\nlet cond_inv_com' env e ct cf l h0 =\n let v = reify (interpret_exp_st e) h0 in\n if v = 0\n then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0)\n else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)\n\n (* Works too but takes 20s more *)\n (* let c = if v = 0 then cf else ct in *)\n (* match reify (interpret_com_st c h0) h0 with *)\n (* | None, _ -> () *)\n (* | Some (), h1 -> () *)\n#reset-options \"--max_fuel 1\"\nlet interpret_cond (e:exp) (ct:com) (cf:com) (h:heap)\n : Lemma (let v = reify (interpret_exp_st e) h in\n let c = if v = 0 then cf else ct in\n (reify (interpret_com_st (If e ct cf) h) h ==\n reify (interpret_com_st c h) h))\n = ()\n\n\nval cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com' env (If e ct cf) l h0))\nlet cond_ni_com' env e ct cf l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else\n let R h0l h0r = h0 in\n let vl = reify (interpret_exp_st e) h0l in\n let vr = reify (interpret_exp_st e) h0r in\n if Low? l\n then begin\n assert (vl == vr) ;\n let c = if vl = 0 then cf else ct in\n assert (ni_com env c l) ;\n let cif = If e ct cf in\n //NS:05/15 ... this 2 should be trivial to prove.\n // Why do they require a lemma?\n interpret_cond e ct cf h0l;\n interpret_cond e ct cf h0r;\n use_ni_com env c l (R h0l h0r)\n end\n else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n match reify (interpret_com_st (If e ct cf) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (If e ct cf) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n cond_inv_com' env e ct cf l h0l ;\n cond_inv_com' env e ct cf l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\n#set-options \"--z3rlimit 5\"\n\nval cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com env (If e ct cf) l))\nlet cond_com env e ct cf l =\n forall_intro\n (fun (h0:rel heap) ->\n cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0))\n\n\n(* Typing rule for Skip\n\n -------------------\n env,pc:High |- skip\n*)\n\nval skip_com : env:label_fun ->\n Lemma (ni_com env Skip High)\nlet skip_com _ = ()\n\n(* While rule for commands\n\n env |- e : l env,pc:l |- c\n -----------------------------------\n env,pc:l |- while (e <> 0) do c\n*)\n\n\nval while_inv_com'\n : env:label_fun ->\n e:exp ->\n c:com ->\n v:metric ->\n l:label ->\n h0:heap ->\n Lemma\n (requires (ni_exp env e l /\\ ni_com env c l))\n (ensures (inv_com' env (While e c v) l h0))\n (decreases (decr_while h0 (While e c v)))\n\n#reset-options \"--z3rlimit 40\"\n\nlet interpret_while_nil e c v h\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n fst (reify (interpret_com_st c h) h) == None))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap)\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n (match reify (interpret_com_st c h) h with\n | None, _ -> True\n | Some _, h' ->\n interpret_exp' h' v >= interpret_exp' h v)))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet rec while_inv_com' env e c v l h0 =\n let v0 = reify (interpret_exp_st e) h0 in\n if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0)\n else\n let m0 = interpret_exp' h0 v in\n match reify (interpret_com_st c h0) h0 with\n | None, _ -> interpret_while_nil e c v h0\n | Some (), h2 ->\n let m1 = interpret_exp' h2 v in\n if m0 > m1\n then begin\n assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ;\n while_inv_com' env e c v l h2\n end\n else interpret_while_loops e c v h0\n\nval while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l /\\ low_equiv env h0 /\\ High? l))\n\nPartial implementation:\nlet while_ni_com'_low_equiv_high env e c v l h0 =\n \n"
},
{
"role": "assistant",
"content": "let R h0l h0r = h0 in\nmatch reify (interpret_com_st (While e c v) h0l) h0l with\n| None, _ -> ()\n| Some (), h1l ->\n match reify (interpret_com_st (While e c v) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n while_inv_com' env e c v l h0l;\n while_inv_com' env e c v l h0r;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: f: (_: Prims.unit -> FStar.Tactics.Effect.Tac a) -> FStar.Tactics.Effect.Tac Prims.unit\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nPartial implementation:\nlet repeat' #a (f: (unit -> Tac a)) : Tac unit =\n \n"
},
{
"role": "assistant",
"content": "let _ = repeat f in\n()"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: _: Prims.unit -> FStar.Tactics.Effect.Tac Prims.unit\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nPartial implementation:\nlet implies_intro' () : Tac unit =\n \n"
},
{
"role": "assistant",
"content": "let _ = implies_intro () in\n()"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: h: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.unit\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\nPartial implementation:\nlet exact_hyp' (h: namedv) : Tac unit =\n \n"
},
{
"role": "assistant",
"content": "exact (pack (Tv_Var h))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: x: a -> FStar.Tactics.PatternMatching.match_res a\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nPartial implementation:\nlet return #a (x: a) : match_res a =\n \n"
},
{
"role": "assistant",
"content": "Success x"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: a: Type0 -> h: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.unit\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\nPartial implementation:\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n \n"
},
{
"role": "assistant",
"content": "let hd = quote (FStar.Squash.return_squash #a) in\nexact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n st: Hacl.Spec.SHA2.Vec.state_spec a m ->\n j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} ->\n i: Prims.nat{i < 8 * Spec.Hash.Definitions.word_length a}\n -> FStar.Pervasives.Lemma\n (ensures\n (let l = Hacl.Spec.SHA2.Vec.lanes a m in\n let ind = 8 * j + i / Spec.Hash.Definitions.word_length a in\n FStar.Seq.Base.index (Lib.IntVector.vec_v (Hacl.Spec.SHA2.Vec.transpose_state8 st).[ ind / l\n ])\n (ind % l) ==\n FStar.Seq.Base.index (Hacl.Spec.SHA2.Vec.state_spec_v st).[ j ]\n (i / Spec.Hash.Definitions.word_length a)))\nEffect: FStar.Pervasives.Lemma\n\nContext:\nmodule Hacl.Spec.SHA2.Lemmas\n\nopen FStar.Mul\nopen Lib.IntTypes\nopen Lib.Sequence\nopen Lib.IntVector\nopen Lib.IntVector.Transpose\n\nopen Spec.Hash.Definitions\nopen Hacl.Spec.SHA2.Vec\n\n\n#set-options \"--z3rlimit 50 --fuel 0 --ifuel 1\"\n\nval transpose_ws4_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws4_lemma_ij #a #m ws j i =\n let l = lanes a m in\n let i_sub = i / l in\n let j_sub = i % l in\n assert (i_sub * l + j_sub == i);\n\n let vs = sub ws (i_sub * l) l in\n eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs);\n //assert ((transpose_ws4 ws).[i] == (sub (transpose_ws4 ws) (i_sub * l) l).[j_sub]);\n //assert ((transpose_ws4 ws).[i] == (transpose4x4_lseq vs).[j_sub]);\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v (transpose4x4_lseq vs).[j_sub]).[j]);\n transpose4x4_lemma vs;\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v vs.[j]).[j_sub]);\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i_sub * l + j]).[j_sub])\n\n\nval transpose_ws8_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 8}\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n (vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws8_lemma_ij #a #m ws j i =\n let l = lanes a m in\n let i_sub = i / l in\n let j_sub = i % l in\n assert (i_sub * l + j_sub == i);\n\n let vs = sub ws (i_sub * l) l in\n eq_intro (sub (transpose_ws8 ws) (i_sub * l) l) (transpose8x8_lseq vs);\n assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v (transpose8x8_lseq vs).[j_sub]).[j]);\n transpose8x8_lemma vs;\n assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i_sub * lanes a m + j]).[j_sub])\n\n\nval transpose_ws_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{is_supported a m}\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws_lemma_ij #a #m ws j i =\n assert (((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v (transpose_ws ws).[i]).[j]);\n match lanes a m with\n | 1 -> ()\n | 4 -> transpose_ws4_lemma_ij #a #m ws j i\n | 8 -> transpose_ws8_lemma_ij #a #m ws j i\n\n\nval transpose_state4_lemma:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 4}\n -> st:state_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 8 * word_length a} ->\n Lemma\n (let l = lanes a m in\n let ind = 8 * j + i / word_length a in\n Seq.index (vec_v (transpose_state st).[ind / l]) (ind % l) ==\n Seq.index (state_spec_v st).[j] (i / word_length a))\n\nlet transpose_state4_lemma #a #m st j i =\n let r0 = transpose4x4_lseq (sub st 0 4) in\n transpose4x4_lemma (sub st 0 4);\n let r1 = transpose4x4_lseq (sub st 4 4) in\n transpose4x4_lemma (sub st 4 4)\n\n\nval transpose_state8_lemma:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 8}\n -> st:state_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 8 * word_length a} ->\n Lemma\n (let l = lanes a m in\n let ind = 8 * j + i / word_length a in\n Seq.index (vec_v (transpose_state8 st).[ind / l]) (ind % l) ==\n Seq.index (state_spec_v st).[j] (i / word_length a))\n\nPartial implementation:\nlet transpose_state8_lemma #a #m st j i =\n \n"
},
{
"role": "assistant",
"content": "let l = lanes a m in\nlet ind = 8 * j + i / word_length a in\nlet r0 = transpose8x8_lseq st in\ntranspose8x8_lemma st"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: ex: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.PatternMatching.match_res a\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nPartial implementation:\nlet raise #a (ex: match_exception) : match_res a =\n \n"
},
{
"role": "assistant",
"content": "Failure ex"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: bindings: FStar.Tactics.PatternMatching.bindings -> FStar.Tactics.Effect.Tac Prims.string\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\nPartial implementation:\nlet string_of_bindings (bindings: bindings) =\n \n"
},
{
"role": "assistant",
"content": "String.concat \"\\n\" (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm)) bindings)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: pat: FStar.Tactics.PatternMatching.pattern -> _: FStar.Tactics.NamedView.term\n -> FStar.Tactics.Effect.Tac\n (FStar.Tactics.PatternMatching.match_res FStar.Tactics.PatternMatching.bindings)\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\n\nPartial implementation:\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n \n"
},
{
"role": "assistant",
"content": "fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Type0\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nPartial implementation:\nlet absvar =\n \n"
},
{
"role": "assistant",
"content": "binding"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: ms: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac Prims.string\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nPartial implementation:\nlet string_of_matching_solution ms =\n \n"
},
{
"role": "assistant",
"content": "let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) -> varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars)\nin\nlet hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) -> nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps)\nin\n\"\\n{ vars: \" ^ vars ^ \"\\n\" ^ \" hyps: \" ^ hyps ^ \" }\""
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n a: Type ->\n solution: FStar.Tactics.PatternMatching.matching_solution ->\n name: FStar.Tactics.PatternMatching.varname\n -> FStar.Tactics.Effect.Tac a\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nPartial implementation:\nlet ms_locate_var (a: Type) (solution: matching_solution) (name: varname) : Tac a =\n \n"
},
{
"role": "assistant",
"content": "unquote #a (assoc_varname_fail name solution.ms_vars)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n env: IfcRulesReify.label_fun ->\n e: WhileReify.exp ->\n c: WhileReify.com ->\n v: WhileReify.metric ->\n l: IfcRulesReify.label ->\n h0: Rel.rel FStar.DM4F.Heap.IntStoreFixed.heap\n -> FStar.Pervasives.Lemma\n (requires\n IfcRulesReify.ni_exp env e l /\\ IfcRulesReify.ni_com env c l /\\\n IfcRulesReify.low_equiv env h0 /\\ Low? l)\n (ensures IfcRulesReify.ni_com' env (WhileReify.While e c v) l h0)\n (decreases\n WhileReify.decr_while (R?.l h0) (WhileReify.While e c v) +\n WhileReify.decr_while (R?.r h0) (WhileReify.While e c v))\nEffect: FStar.Pervasives.Lemma\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\nmodule IfcRulesReify\n\nopen Rel\nopen WhileReify\nopen FStar.DM4F.Heap.IntStoreFixed\nopen FStar.DM4F.IntStoreExcFixed\nopen FStar.Squash\nopen FStar.Classical\n\n(****************************** Preliminaries ******************************)\n\n(* CH: Everything specialized to 2-point lattice *)\ntype label =\n| Low\n| High\n\nval op_Less : label -> label -> Tot bool\nlet op_Less l1 l2 =\n match l1, l2 with\n | Low,High -> true\n | _, _ -> false\n\nval op_Less_Equals : label -> label -> Tot bool\nlet op_Less_Equals l1 l2 =\n match l1, l2 with\n | High,Low -> false\n | _, _ -> true\n\nval join : label -> label -> Tot label\nlet join l1 l2 =\n match l1, l2 with\n | Low,Low -> Low\n | _, _ -> High\n\nval meet : label -> label -> Tot label\nlet meet l1 l2 =\n match l1, l2 with\n | High, High -> High\n | _, _ -> Low\n\nlet universal_property_meet l l1 l2\n : Lemma (requires (l <= l1 /\\ l <= l2)) (ensures (l <= meet l1 l2))\n= ()\n\ntype label_fun = id -> Tot label\n\ntype low_equiv (env:label_fun) (h1:rel heap) =\n (forall (x:id). (* {:pattern (env x)} *) env x = Low ==> index (R?.l h1) x = index (R?.r h1) x)\n\n(**************************** Typing Judgements ****************************)\n\n(* env |- e : l\n - Expressions do not modify the heap\n - Correctness\n - Low equivalent input heaps + Low label ==> same result\n*)\nlet ni_exp (env:label_fun) (e:exp) (l:label) : Tot Type0 =\n forall (h: rel heap). (* {:pattern (low_equiv env h)} *)\n (low_equiv env h /\\ Low? l) ==>\n (* interpret_exp (R?.r h) e = interpret_exp (R?.l h) e *)\n begin\n let vr = reify (interpret_exp_st e) (R?.r h)in\n let vl = reify (interpret_exp_st e) (R?.l h) in\n vr = vl\n end\n\n\n\n(* env,pc:l |- c\n - References with a label below l are not modified\n - Total correctness\n - Low equivalent input heaps ==> Low equivalent output heaps\n*)\nlet inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Tot Type0\n=\n match interpret_com h0 c with\n | None -> True\n | Some h1 ->\n forall (i:id). (* {:pattern (env i < l)} *) env i < l ==> index h0 i = index h1 i\n\nlet ni_com' (env:label_fun) (c:com) (l:label) (h0:rel heap) : Tot Type0 =\n let R h0l h0r = h0 in\n (* KM : That's the code that we would like to write but subtyping and matching on pairs interplay badly *)\n (* it generates a VC which boils down to [forall (h1l:heap). length h1l = length h0l] which is obviously false *)\n (* begin match interpret_com h0l c, interpret_com h0r c with *)\n (* | Some h1l, Some h1r -> low_equiv env (R h0l h0r) ==> low_equiv env (R h1l h1r) *)\n (* | _ -> True *)\n (* end *)\n begin match interpret_com h0l c with\n | Some h1l -> begin match interpret_com h0r c with\n | Some h1r -> low_equiv env h0 ==> low_equiv env (R h1l h1r)\n | _ -> True\n end\n | _ -> True\n end\n\nlet ni_com (env:label_fun) (c:com) (l:label) : Tot Type0 =\n (forall (h0: rel heap). (* {:pattern (low_equiv env h0)} *) ni_com' env c l h0) /\\\n (forall (h0:heap). (* {:pattern (Some? (interpret_com h0 c))} *) inv_com' env c l h0)\n\n(*********************** Typing Rules for Expressions **********************)\n\n(* CH: The way we derive these rules looks more like a\n semantically-justified program logic than a syntactic type\n system. Any connection to Dave Naumann and Anindya Banerjee's\n \"relational logic\"? (e.g. https://arxiv.org/abs/1611.08992) *)\n\n(* Subtyping rule for expression labels\n\n E |- e : l1 l1 <= l2\n ----------------------\n E |- e : l2\n*)\nval sub_exp : env:label_fun -> e:exp -> l1:label -> l2:label ->\n Lemma (requires (l1 <= l2 /\\ ni_exp env e l1))\n (ensures (ni_exp env e l2))\nlet sub_exp _ _ _ _ = ()\n\n\n\n(* Typing rule for dereferencing\n\n ----------------\n E | - r : E(r)\n*)\n\nval avar_exp : env:label_fun -> r:id ->\n Lemma (ensures (ni_exp env (AVar r) (env r)))\nlet avar_exp _ _ = ()\n\n(* Typing rule for Int constants\n\n i : int\n -------\n i : Low\n*)\nval aint_exp : env:label_fun -> i:int ->\n Lemma (requires True)\n (ensures (ni_exp env (AInt i) Low))\nlet aint_exp _ _ = ()\n\n\n(* Typing rule for binary operators\n\n e1 : l e2 : l\n ----------------\n e1 `op` e2 : l\n*)\n\nval binop_exp : env:label_fun -> op:binop -> e1:exp -> e2:exp -> l:label ->\n Lemma (requires (ni_exp env e1 l) /\\ (ni_exp env e2 l))\n (ensures (ni_exp env (AOp op e1 e2) l))\nlet binop_exp env op e1 e2 l =\n ()\n\n(************************ Typing Rules for Commands ************************)\n\n(* Subtyping rule for commands\n\n env,pc:l1 |- c l2 <= l1\n ---------------------------\n env,pc:l2 |- c\n*)\n\nval sub_com : env:label_fun -> c:com -> l1:label -> l2:label ->\n Lemma (requires (l2 <= l1 /\\ ni_com env c l1 ))\n (ensures (ni_com env c l2 ))\nlet sub_com _ _ _ _ = ()\n\n\n(* Typing rule for assignment\n\n env |- e : env(r)\n ------------------------\n env, pc:env(r) |- r := e\n\n - label of expression and context label have to be below label of r\n (first one to prevent explicit, second to prevent implicit flows)\n*)\n\nlet assign_inv_com0 (env:label_fun) (e:exp) (r:id) (ne:squash(ni_exp env e (env r))) (h0:rel heap)\n : Lemma (ni_com' env (Assign r e) (env r) h0)\n=\n FStar.Squash.give_proof ne ;\n let vr = reify (interpret_exp_st e) (R?.r h0) in\n let vl = reify (interpret_exp_st e) (R?.l h0) in\n match reify (interpret_com_st (Assign r e) (R?.l h0)) (R?.l h0) with\n | Some (), h1l ->\n begin match reify (interpret_com_st (Assign r e) (R?.r h0)) (R?.r h0) with\n | Some (), h1r -> assert (h1l = upd (R?.l h0) r vl /\\ h1r = upd (R?.r h0) r vr)\n | None, _ -> ()\n end\n | None, _ -> ()\n\nlet assign_inv_com' (env:label_fun) (e:exp) (r:id) (h0:heap)\n : Lemma (inv_com' env (Assign r e) (env r) h0)\n=\n let v = reify (interpret_exp_st e) h0 in\n match reify (interpret_com_st (Assign r e) h0) h0 with\n | None, h1 -> ()\n | Some (), h1 ->\n assert (h1 == upd h0 r v)\n\nval assign_com : env:label_fun -> e:exp -> r:id ->\n Lemma (requires (ni_exp env e (env r)))\n (ensures (ni_com env (Assign r e) (env r)))\nlet assign_com env e r =\n forall_intro (assign_inv_com0 env e r (FStar.Squash.get_proof (ni_exp env e (env r)))) ;\n forall_intro (assign_inv_com' env e r)\n\n\nlet seq_nil1 (c1:com) (c2:com) (h:heap)\n : Lemma\n (requires (fst (reify (interpret_com_st c1 h) h) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h) h) = None))\n = ()\n\nlet seq_nil2 (c1:com) (c2:com) (h0:heap) (h1:heap)\n : Lemma\n (requires (h1 == snd (reify (interpret_com_st c1 h0) h0) /\\\n fst (reify (interpret_com_st c2 h1) h1) = None))\n (ensures (fst (reify (interpret_com_st (Seq c1 c2) h0) h0) = None))\n = ()\n\n(* Sequencing rule for commands\n\n env,pc:l |- c1 env,pc:l |- c2\n ------------------------------\n env,pc:l |- c1; c2\n*)\n\nval seq_inv_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0:heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (inv_com' env (Seq c1 c2) l h0))\nlet seq_inv_com' env c1 c2 l h0 =\n match reify (interpret_com_st c1 h0) h0 with\n | None, _ -> seq_nil1 c1 c2 h0\n | Some (), h1 ->\n match reify (interpret_com_st c2 h1) h1 with\n | None, _ -> seq_nil2 c1 c2 h0 h1\n | Some (), h2 -> ()\n\n#set-options \"--z3rlimit 50\"\nlet use_ni_com (env:label_fun) (c:com) (l:label) (h:rel heap{low_equiv env h})\n : Lemma\n (requires ni_com env c l)\n (ensures\n (let R hl hr = h in\n match reify (interpret_com_st c hl) hl,\n reify (interpret_com_st c hr) hr with\n | (Some _, hl'),\n (Some _, hr') -> low_equiv env (R hl' hr')\n | _ -> True))\n = ()\n\nval seq_com' : env:label_fun -> c1:com -> c2:com -> l:label -> h0: rel heap ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com' env (Seq c1 c2) l h0))\nlet seq_com' env c1 c2 l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else begin\n assert (low_equiv env h0);\n let R h0l h0r = h0 in\n match reify (interpret_com_st c1 h0l) h0l with\n | None, _ -> seq_nil1 c1 c2 h0l\n | Some (), h1l ->\n match reify (interpret_com_st c1 h0r) h0r with\n | None, _ -> seq_nil1 c1 c2 h0r\n | Some (), h1r ->\n match reify (interpret_com_st c2 h1l) h1l with\n | None, _ -> seq_nil2 c1 c2 h0l h1l\n | Some (), h2l ->\n match reify (interpret_com_st c2 h1r) h1r with\n | None, _ -> seq_nil2 c1 c2 h0r h1r\n | Some (), h2r ->\n let h1 = R h1l h1r in\n use_ni_com env c1 l h0;\n assert (low_equiv env h1) ;\n let h2 = R h2l h2r in\n use_ni_com env c2 l h1;\n assert (low_equiv env h2)\n end\n\nval seq_com : env:label_fun -> c1:com -> c2:com -> l:label ->\n Lemma (requires (ni_com env c1 l /\\ ni_com env c2 l))\n (ensures (ni_com env (Seq c1 c2) l))\nlet seq_com env c1 c2 l =\n forall_intro\n (fun (h0:rel heap) ->\n seq_com' env c1 c2 l h0 <: Lemma (ni_com' env (Seq c1 c2) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n seq_inv_com' env c1 c2 l h0 <: Lemma (inv_com' env (Seq c1 c2) l h0))\n\n(* Typing rule for conditional commands\n\n env |- e : l env,pc:l |- ct env,pc:l |- cf\n ----------------------------------------------\n env,pc:l |- if e <> 0 then ct else cf\n*)\n\n(* let project_inv_com' (env:label_fun) (c:com) (l:label) (h0:heap) : Lemma (requires (ni_com env c l)) (ensures (inv_com' env c l h0)) = () *)\n\nval cond_inv_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (inv_com' env (If e ct cf) l h0))\nlet cond_inv_com' env e ct cf l h0 =\n let v = reify (interpret_exp_st e) h0 in\n if v = 0\n then assert (inv_com' env cf l h0 ==> inv_com' env (If e ct cf) l h0)\n else assert (inv_com' env ct l h0 ==> inv_com' env (If e ct cf) l h0)\n\n (* Works too but takes 20s more *)\n (* let c = if v = 0 then cf else ct in *)\n (* match reify (interpret_com_st c h0) h0 with *)\n (* | None, _ -> () *)\n (* | Some (), h1 -> () *)\n#reset-options \"--max_fuel 1\"\nlet interpret_cond (e:exp) (ct:com) (cf:com) (h:heap)\n : Lemma (let v = reify (interpret_exp_st e) h in\n let c = if v = 0 then cf else ct in\n (reify (interpret_com_st (If e ct cf) h) h ==\n reify (interpret_com_st c h) h))\n = ()\n\n\nval cond_ni_com' : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label -> h0:rel heap ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com' env (If e ct cf) l h0))\nlet cond_ni_com' env e ct cf l h0 =\n if not (FStar.StrongExcludedMiddle.strong_excluded_middle (low_equiv env h0))\n then ()\n else\n let R h0l h0r = h0 in\n let vl = reify (interpret_exp_st e) h0l in\n let vr = reify (interpret_exp_st e) h0r in\n if Low? l\n then begin\n assert (vl == vr) ;\n let c = if vl = 0 then cf else ct in\n assert (ni_com env c l) ;\n let cif = If e ct cf in\n //NS:05/15 ... this 2 should be trivial to prove.\n // Why do they require a lemma?\n interpret_cond e ct cf h0l;\n interpret_cond e ct cf h0r;\n use_ni_com env c l (R h0l h0r)\n end\n else (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n match reify (interpret_com_st (If e ct cf) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (If e ct cf) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n cond_inv_com' env e ct cf l h0l ;\n cond_inv_com' env e ct cf l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\n#set-options \"--z3rlimit 5\"\n\nval cond_com : env:label_fun -> e:exp -> ct:com -> cf:com -> l:label ->\n Lemma (requires ((ni_exp env e l) /\\ (ni_com env ct l) /\\ (ni_com env cf l)))\n (ensures (ni_com env (If e ct cf) l))\nlet cond_com env e ct cf l =\n forall_intro\n (fun (h0:rel heap) ->\n cond_ni_com' env e ct cf l h0 <: Lemma (ni_com' env (If e ct cf) l h0)) ;\n forall_intro\n (fun (h0:heap) ->\n cond_inv_com' env e ct cf l h0 <: Lemma (inv_com' env (If e ct cf) l h0))\n\n\n(* Typing rule for Skip\n\n -------------------\n env,pc:High |- skip\n*)\n\nval skip_com : env:label_fun ->\n Lemma (ni_com env Skip High)\nlet skip_com _ = ()\n\n(* While rule for commands\n\n env |- e : l env,pc:l |- c\n -----------------------------------\n env,pc:l |- while (e <> 0) do c\n*)\n\n\nval while_inv_com'\n : env:label_fun ->\n e:exp ->\n c:com ->\n v:metric ->\n l:label ->\n h0:heap ->\n Lemma\n (requires (ni_exp env e l /\\ ni_com env c l))\n (ensures (inv_com' env (While e c v) l h0))\n (decreases (decr_while h0 (While e c v)))\n\n#reset-options \"--z3rlimit 40\"\n\nlet interpret_while_nil e c v h\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n fst (reify (interpret_com_st c h) h) == None))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet interpret_while_loops (e:exp) (c:com) (v:metric) (h:heap)\n : Lemma (requires (reify (interpret_exp_st e) h <> 0 /\\\n (match reify (interpret_com_st c h) h with\n | None, _ -> True\n | Some _, h' ->\n interpret_exp' h' v >= interpret_exp' h v)))\n (ensures (interpret_com h (While e c v) == None))\n = ()\n\nlet rec while_inv_com' env e c v l h0 =\n let v0 = reify (interpret_exp_st e) h0 in\n if v0 = 0 then assert (interpret_com h0 (While e c v) == Some h0)\n else\n let m0 = interpret_exp' h0 v in\n match reify (interpret_com_st c h0) h0 with\n | None, _ -> interpret_while_nil e c v h0\n | Some (), h2 ->\n let m1 = interpret_exp' h2 v in\n if m0 > m1\n then begin\n assert (decr_while h2 (While e c v) << decr_while h0 (While e c v)) ;\n while_inv_com' env e c v l h2\n end\n else interpret_while_loops e c v h0\n\nval while_ni_com'_low_equiv_high : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l /\\ low_equiv env h0 /\\ High? l))\n (ensures (ni_com' env (While e c v) l h0))\nlet while_ni_com'_low_equiv_high env e c v l h0 =\n (* h0 and h1 are low_equiv since cl and cr cannot write at low cells *)\n let R h0l h0r = h0 in\n match reify (interpret_com_st (While e c v) h0l) h0l with\n | None, _ -> ()\n | Some (), h1l ->\n match reify (interpret_com_st (While e c v) h0r) h0r with\n | None, _ -> ()\n | Some (), h1r ->\n while_inv_com' env e c v l h0l ;\n while_inv_com' env e c v l h0r ;\n assert (low_equiv env h0 ==> low_equiv env (R h1l h1r))\n\nval while_ni_com'_low_equiv_low : env:label_fun -> e:exp -> c:com -> v:metric -> l:label -> h0:rel heap ->\n Lemma (requires (ni_exp env e l /\\ ni_com env c l /\\ low_equiv env h0 /\\ Low? l))\n (ensures (ni_com' env (While e c v) l h0))\n\nPartial implementation:\nlet rec while_ni_com'_low_equiv_low env e c v l h0 =\n \n"
},
{
"role": "assistant",
"content": "let R h0l h0r = h0 in\nlet v0l = reify (interpret_exp_st e) h0l in\nlet v0r = reify (interpret_exp_st e) h0r in\nassert (v0l == v0r);\nif v0l = 0\nthen\n (assert (interpret_com h0l (While e c v) == Some h0l);\n assert (interpret_com h0r (While e c v) == Some h0r))\nelse\n let m0l = interpret_exp' h0l v in\n let m0r = interpret_exp' h0r v in\n match reify (interpret_com_st c h0l) h0l with\n | None, _ -> interpret_while_nil e c v h0l\n | Some (), h2l ->\n match reify (interpret_com_st c h0r) h0r with\n | None, _ -> interpret_while_nil e c v h0r\n | Some (), h2r ->\n let m1l = interpret_exp' h2l v in\n let m1r = interpret_exp' h2r v in\n if m0l > m1l\n then\n if m0r > m1r\n then\n (assert (decr_while h2l (While e c v) << decr_while h0l (While e c v));\n while_ni_com'_low_equiv_low env e c v l (R h2l h2r))\n else interpret_while_loops e c v h0r\n else interpret_while_loops e c v h0l"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n a: Type ->\n solution: FStar.Tactics.PatternMatching.matching_solution ->\n name: FStar.Tactics.PatternMatching.varname\n -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.hypothesis\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nPartial implementation:\nlet ms_locate_hyp (a: Type) (solution: matching_solution) (name: varname) : Tac hypothesis =\n \n"
},
{
"role": "assistant",
"content": "assoc_varname_fail name solution.ms_hyps"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Prims.string\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nPartial implementation:\nlet hyp_qn =\n \n"
},
{
"role": "assistant",
"content": "`%hyp"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Prims.string\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nPartial implementation:\nlet goal_qn =\n \n"
},
{
"role": "assistant",
"content": "`%pm_goal"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: a: Type -> Prims.eqtype\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\n\nPartial implementation:\nlet pm_goal (a: Type) =\n \n"
},
{
"role": "assistant",
"content": "unit"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: x: FStar.Tactics.NamedView.namedv -> FStar.Tactics.Effect.Tac Prims.string\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\nPartial implementation:\nlet name_of_namedv (x: namedv) : Tac string =\n \n"
},
{
"role": "assistant",
"content": "unseal (inspect_namedv x).ppname"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: Type0\nEffect: Prims.Tot\n\nContext:\nmodule MerkleTree.Spec\n\nopen FStar.Classical\nopen FStar.Mul\nopen FStar.Seq\n\nmodule S = FStar.Seq\n\n#set-options \"--max_fuel 0 --max_ifuel 0 --z3rlimit 10\"\n\n// For SHA2_256, this is is a sequence of 32 bytes\n// These are secret bytes, hence not an eqtype\ntype hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz }\n\ntype hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz)\n\nval sha256_compress: hash_fun_t #32\nlet sha256_compress src1 src2 =\n let sz = Spec.Hash.Definitions.SHA2_256 in\n let hash_alg = Spec.Hash.Definitions.SHA2_256 in\n let acc = Spec.Agile.Hash.init hash_alg in\n let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in\n Spec.Agile.Hash.finish hash_alg acc ()\n\n/// For simplicity, we will specify the root for a sequence of [i]\n/// tags where [i <= 2^n] as the root of a full binary tree with [2^n]\n/// leaves obtained by padding the sequence with dummies. This\n/// requires extending the definitions of hashes and hash functions. Our\n/// extended definition of hash justifies skipping any concrete\n/// computation on dummies.\nnoeq\ntype padded_hash #hsz =\n| HRaw: hr:hash #hsz -> padded_hash #hsz\n| HPad // right padding to make the size of a Merkle tree a power of 2\n\nval padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)\nlet padded_hash_fun #hsz f lh rh =\n allow_inversion (padded_hash #hsz);\n match lh, rh with\n | HPad , _ -> HPad\n | _ , HPad -> lh\n | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)\n\nnoextract\n\nPartial implementation:\nlet hashes #hsz =\n \n"
},
{
"role": "assistant",
"content": "S.seq (padded_hash #hsz)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: a: Type -> Type0\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\nPartial implementation:\nlet hyp (a: Type) =\n \n"
},
{
"role": "assistant",
"content": "binding"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: nb: FStar.Tactics.NamedView.binder -> FStar.Tactics.NamedView.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nPartial implementation:\nlet type_of_named_binder (nb: binder) : term =\n \n"
},
{
"role": "assistant",
"content": "nb.sort"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: tm: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n\nPartial implementation:\nlet beta_reduce (tm: term) : Tac term =\n \n"
},
{
"role": "assistant",
"content": "norm_term [] tm"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: t: FStar.Tactics.NamedView.term -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nPartial implementation:\nlet cleanup_abspat (t: term) : Tac term =\n \n"
},
{
"role": "assistant",
"content": "norm_term [] t"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n ws: Hacl.Spec.SHA2.Vec.ws_spec a m ->\n j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} ->\n i: Prims.nat{i < 16}\n -> FStar.Pervasives.Lemma\n (ensures\n (let l = Hacl.Spec.SHA2.Vec.lanes a m in\n (Lib.IntVector.vec_v (Hacl.Spec.SHA2.Vec.transpose_ws4 ws).[ i ]).[ j ] ==\n (Lib.IntVector.vec_v ws.[ (i / l) * l + j ]).[ i % l ]))\nEffect: FStar.Pervasives.Lemma\n\nContext:\nmodule Hacl.Spec.SHA2.Lemmas\n\nopen FStar.Mul\nopen Lib.IntTypes\nopen Lib.Sequence\nopen Lib.IntVector\nopen Lib.IntVector.Transpose\n\nopen Spec.Hash.Definitions\nopen Hacl.Spec.SHA2.Vec\n\n\n#set-options \"--z3rlimit 50 --fuel 0 --ifuel 1\"\n\nval transpose_ws4_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])\n\nPartial implementation:\nlet transpose_ws4_lemma_ij #a #m ws j i =\n \n"
},
{
"role": "assistant",
"content": "let l = lanes a m in\nlet i_sub = i / l in\nlet j_sub = i % l in\nassert (i_sub * l + j_sub == i);\nlet vs = sub ws (i_sub * l) l in\neq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs);\nassert ((vec_v (transpose_ws4 ws).[ i ]).[ j ] == (vec_v (transpose4x4_lseq vs).[ j_sub ]).[ j ]);\ntranspose4x4_lemma vs;\nassert ((vec_v (transpose_ws4 ws).[ i ]).[ j ] == (vec_v vs.[ j ]).[ j_sub ]);\nassert ((vec_v (transpose_ws4 ws).[ i ]).[ j ] == (vec_v ws.[ i_sub * l + j ]).[ j_sub ])"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: nb: FStar.Tactics.NamedView.binder -> FStar.Tactics.Effect.Tac Prims.string\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\nPartial implementation:\nlet name_of_named_binder (nb: binder) : Tac string =\n \n"
},
{
"role": "assistant",
"content": "unseal nb.ppname"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n continuation: FStar.Tactics.PatternMatching.abspat_continuation ->\n solution_term: FStar.Tactics.NamedView.term\n -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n\nPartial implementation:\nlet specialize_abspat_continuation' (continuation: abspat_continuation) (solution_term: term)\n : Tac term =\n \n"
},
{
"role": "assistant",
"content": "let mk_arg_term argspec = abspat_arg_of_abspat_argspec solution_term argspec in\nlet argspecs, body = continuation in\nhoist_and_apply body (map mk_arg_term argspecs) []"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: a: Type0 -> continuation: FStar.Tactics.PatternMatching.abspat_continuation\n -> FStar.Tactics.Effect.Tac\n (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a)\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n \nlet specialize_abspat_continuation' (continuation: abspat_continuation)\n (solution_term:term)\n : Tac term =\n let mk_arg_term argspec =\n abspat_arg_of_abspat_argspec solution_term argspec in\n let argspecs, body = continuation in\n hoist_and_apply body (map mk_arg_term argspecs) []\n\n(** Specialize a continuation of type ``abspat_continuation``. This yields a\nquoted function taking a matching solution and running its body with appropriate\nbindings. **)\nlet specialize_abspat_continuation (continuation: abspat_continuation)\n : Tac term =\n let solution_binder = fresh_binder (`matching_solution) in\n let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in\n let applied = specialize_abspat_continuation' continuation solution_term in\n let thunked = pack (Tv_Abs solution_binder applied) in\n debug (\"Specialized into \" ^ (term_to_string thunked));\n let normalized = beta_reduce thunked in\n debug (\"… which reduces to \" ^ (term_to_string normalized));\n thunked\n\n(** Interpret a continuation of type ``abspat_continuation``.\nThis yields a function taking a matching solution and running the body of the\n\nPartial implementation:\nlet interp_abspat_continuation (a: Type0) (continuation: abspat_continuation)\n : Tac (matching_solution -> Tac a) =\n \n"
},
{
"role": "assistant",
"content": "let applied = specialize_abspat_continuation continuation in\nunquote #(matching_solution -> Tac a) applied"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: s: FStar.Seq.Base.seq MerkleTree.Spec.padded_hash -> i: Prims.nat{i < FStar.Seq.Base.length s}\n -> MerkleTree.Spec.padded_hash\nEffect: Prims.Tot\n\nContext:\nmodule MerkleTree.Spec\n\nopen FStar.Classical\nopen FStar.Mul\nopen FStar.Seq\n\nmodule S = FStar.Seq\n\n#set-options \"--max_fuel 0 --max_ifuel 0 --z3rlimit 10\"\n\n// For SHA2_256, this is is a sequence of 32 bytes\n// These are secret bytes, hence not an eqtype\ntype hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz }\n\ntype hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz)\n\nval sha256_compress: hash_fun_t #32\nlet sha256_compress src1 src2 =\n let sz = Spec.Hash.Definitions.SHA2_256 in\n let hash_alg = Spec.Hash.Definitions.SHA2_256 in\n let acc = Spec.Agile.Hash.init hash_alg in\n let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in\n Spec.Agile.Hash.finish hash_alg acc ()\n\n/// For simplicity, we will specify the root for a sequence of [i]\n/// tags where [i <= 2^n] as the root of a full binary tree with [2^n]\n/// leaves obtained by padding the sequence with dummies. This\n/// requires extending the definitions of hashes and hash functions. Our\n/// extended definition of hash justifies skipping any concrete\n/// computation on dummies.\nnoeq\ntype padded_hash #hsz =\n| HRaw: hr:hash #hsz -> padded_hash #hsz\n| HPad // right padding to make the size of a Merkle tree a power of 2\n\nval padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)\nlet padded_hash_fun #hsz f lh rh =\n allow_inversion (padded_hash #hsz);\n match lh, rh with\n | HPad , _ -> HPad\n | _ , HPad -> lh\n | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)\n\nnoextract\nval hashes (#hsz:pos): Type0\nlet hashes #hsz = S.seq (padded_hash #hsz)\n\ntype merkle_tree (#hsz:pos) n = hs:hashes #hsz {S.length hs = pow2 n}\n\nval mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz)\nlet mt_get #_ #_ mt idx = S.index mt idx\n\nPartial implementation:\nlet ( .[] ) (#hsz: pos) =\n \n"
},
{
"role": "assistant",
"content": "S.index #(padded_hash #hsz)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: abspat: a -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.matching_solution\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n \nlet specialize_abspat_continuation' (continuation: abspat_continuation)\n (solution_term:term)\n : Tac term =\n let mk_arg_term argspec =\n abspat_arg_of_abspat_argspec solution_term argspec in\n let argspecs, body = continuation in\n hoist_and_apply body (map mk_arg_term argspecs) []\n\n(** Specialize a continuation of type ``abspat_continuation``. This yields a\nquoted function taking a matching solution and running its body with appropriate\nbindings. **)\nlet specialize_abspat_continuation (continuation: abspat_continuation)\n : Tac term =\n let solution_binder = fresh_binder (`matching_solution) in\n let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in\n let applied = specialize_abspat_continuation' continuation solution_term in\n let thunked = pack (Tv_Abs solution_binder applied) in\n debug (\"Specialized into \" ^ (term_to_string thunked));\n let normalized = beta_reduce thunked in\n debug (\"… which reduces to \" ^ (term_to_string normalized));\n thunked\n\n(** Interpret a continuation of type ``abspat_continuation``.\nThis yields a function taking a matching solution and running the body of the\ncontinuation with appropriate bindings. **)\nlet interp_abspat_continuation (a:Type0) (continuation: abspat_continuation)\n : Tac (matching_solution -> Tac a) =\n let applied = specialize_abspat_continuation continuation in\n unquote #(matching_solution -> Tac a) applied\n\n/// Putting it all together\n/// =======================\n///\n/// We now have all we need to use pattern-matching, short of a few convenience functions:\n\n(** Construct a matching problem from an abspat. **)\nlet interp_abspat #a (abspat: a)\n : Tac (matching_problem * abspat_continuation) =\n matching_problem_of_abs (quote abspat)\n\n(** Construct an solve a matching problem.\nThis higher-order function isn't very usable on its own — it's mostly a\nconvenience function to avoid duplicating the problem-parsing code. **)\nlet match_abspat #b #a (abspat: a)\n (k: abspat_continuation -> Tac (matching_solution -> Tac b))\n : Tac b =\n let goal = cur_goal () in\n let hypotheses = vars_of_env (cur_env ()) in\n let problem, continuation = interp_abspat abspat in\n solve_mp problem hypotheses goal (k continuation)\n\n(** Inspect the matching problem produced by parsing an abspat. **)\nlet inspect_abspat_problem #a (abspat: a) : Tac matching_problem =\n fst (interp_abspat #a abspat)\n\nPartial implementation:\nlet inspect_abspat_solution #a (abspat: a) : Tac matching_solution =\n \n"
},
{
"role": "assistant",
"content": "match_abspat abspat (fun _ -> (fun solution -> solution <: Tac _) <: Tac _)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: continuation: FStar.Tactics.PatternMatching.abspat_continuation\n -> FStar.Tactics.Effect.Tac FStar.Tactics.NamedView.term\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n \nlet specialize_abspat_continuation' (continuation: abspat_continuation)\n (solution_term:term)\n : Tac term =\n let mk_arg_term argspec =\n abspat_arg_of_abspat_argspec solution_term argspec in\n let argspecs, body = continuation in\n hoist_and_apply body (map mk_arg_term argspecs) []\n\n(** Specialize a continuation of type ``abspat_continuation``. This yields a\nquoted function taking a matching solution and running its body with appropriate\n\nPartial implementation:\nlet specialize_abspat_continuation (continuation: abspat_continuation) : Tac term =\n \n"
},
{
"role": "assistant",
"content": "let solution_binder = fresh_binder (`matching_solution) in\nlet solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in\nlet applied = specialize_abspat_continuation' continuation solution_term in\nlet thunked = pack (Tv_Abs solution_binder applied) in\ndebug (\"Specialized into \" ^ (term_to_string thunked));\nlet normalized = beta_reduce thunked in\ndebug (\"\\226\\128\\166 which reduces to \" ^ (term_to_string normalized));\nthunked"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: _: FStar.Tactics.PatternMatching.pattern -> Prims.string\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nPartial implementation:\nlet desc_of_pattern =\n \n"
},
{
"role": "assistant",
"content": "function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\""
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: abspat: a -> FStar.Tactics.Effect.Tac FStar.Tactics.PatternMatching.matching_problem\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n \nlet specialize_abspat_continuation' (continuation: abspat_continuation)\n (solution_term:term)\n : Tac term =\n let mk_arg_term argspec =\n abspat_arg_of_abspat_argspec solution_term argspec in\n let argspecs, body = continuation in\n hoist_and_apply body (map mk_arg_term argspecs) []\n\n(** Specialize a continuation of type ``abspat_continuation``. This yields a\nquoted function taking a matching solution and running its body with appropriate\nbindings. **)\nlet specialize_abspat_continuation (continuation: abspat_continuation)\n : Tac term =\n let solution_binder = fresh_binder (`matching_solution) in\n let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in\n let applied = specialize_abspat_continuation' continuation solution_term in\n let thunked = pack (Tv_Abs solution_binder applied) in\n debug (\"Specialized into \" ^ (term_to_string thunked));\n let normalized = beta_reduce thunked in\n debug (\"… which reduces to \" ^ (term_to_string normalized));\n thunked\n\n(** Interpret a continuation of type ``abspat_continuation``.\nThis yields a function taking a matching solution and running the body of the\ncontinuation with appropriate bindings. **)\nlet interp_abspat_continuation (a:Type0) (continuation: abspat_continuation)\n : Tac (matching_solution -> Tac a) =\n let applied = specialize_abspat_continuation continuation in\n unquote #(matching_solution -> Tac a) applied\n\n/// Putting it all together\n/// =======================\n///\n/// We now have all we need to use pattern-matching, short of a few convenience functions:\n\n(** Construct a matching problem from an abspat. **)\nlet interp_abspat #a (abspat: a)\n : Tac (matching_problem * abspat_continuation) =\n matching_problem_of_abs (quote abspat)\n\n(** Construct an solve a matching problem.\nThis higher-order function isn't very usable on its own — it's mostly a\nconvenience function to avoid duplicating the problem-parsing code. **)\nlet match_abspat #b #a (abspat: a)\n (k: abspat_continuation -> Tac (matching_solution -> Tac b))\n : Tac b =\n let goal = cur_goal () in\n let hypotheses = vars_of_env (cur_env ()) in\n let problem, continuation = interp_abspat abspat in\n solve_mp problem hypotheses goal (k continuation)\n\nPartial implementation:\nlet inspect_abspat_problem #a (abspat: a) : Tac matching_problem =\n \n"
},
{
"role": "assistant",
"content": "fst (interp_abspat #a abspat)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: x: a -> FStar.Tactics.Effect.Tac (_: b -> FStar.Tactics.Effect.Tac (a * b))\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n \nlet specialize_abspat_continuation' (continuation: abspat_continuation)\n (solution_term:term)\n : Tac term =\n let mk_arg_term argspec =\n abspat_arg_of_abspat_argspec solution_term argspec in\n let argspecs, body = continuation in\n hoist_and_apply body (map mk_arg_term argspecs) []\n\n(** Specialize a continuation of type ``abspat_continuation``. This yields a\nquoted function taking a matching solution and running its body with appropriate\nbindings. **)\nlet specialize_abspat_continuation (continuation: abspat_continuation)\n : Tac term =\n let solution_binder = fresh_binder (`matching_solution) in\n let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in\n let applied = specialize_abspat_continuation' continuation solution_term in\n let thunked = pack (Tv_Abs solution_binder applied) in\n debug (\"Specialized into \" ^ (term_to_string thunked));\n let normalized = beta_reduce thunked in\n debug (\"… which reduces to \" ^ (term_to_string normalized));\n thunked\n\n(** Interpret a continuation of type ``abspat_continuation``.\nThis yields a function taking a matching solution and running the body of the\ncontinuation with appropriate bindings. **)\nlet interp_abspat_continuation (a:Type0) (continuation: abspat_continuation)\n : Tac (matching_solution -> Tac a) =\n let applied = specialize_abspat_continuation continuation in\n unquote #(matching_solution -> Tac a) applied\n\n/// Putting it all together\n/// =======================\n///\n/// We now have all we need to use pattern-matching, short of a few convenience functions:\n\n(** Construct a matching problem from an abspat. **)\nlet interp_abspat #a (abspat: a)\n : Tac (matching_problem * abspat_continuation) =\n matching_problem_of_abs (quote abspat)\n\n(** Construct an solve a matching problem.\nThis higher-order function isn't very usable on its own — it's mostly a\nconvenience function to avoid duplicating the problem-parsing code. **)\nlet match_abspat #b #a (abspat: a)\n (k: abspat_continuation -> Tac (matching_solution -> Tac b))\n : Tac b =\n let goal = cur_goal () in\n let hypotheses = vars_of_env (cur_env ()) in\n let problem, continuation = interp_abspat abspat in\n solve_mp problem hypotheses goal (k continuation)\n\n(** Inspect the matching problem produced by parsing an abspat. **)\nlet inspect_abspat_problem #a (abspat: a) : Tac matching_problem =\n fst (interp_abspat #a abspat)\n\n(** Inspect the matching solution produced by parsing and solving an abspat. **)\nlet inspect_abspat_solution #a (abspat: a) : Tac matching_solution =\n match_abspat abspat (fun _ -> (fun solution -> solution <: Tac _) <: Tac _)\n\nPartial implementation:\nlet tpair #a #b (x: a) : Tac (b -> Tac (a * b)) =\n \n"
},
{
"role": "assistant",
"content": "fun (y: b) -> (x, y)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: g: Pulse.Typing.Env.env -> p: Pulse.Syntax.Base.term\n -> FStar.Tactics.Effect.Tac\n (Prims.dtuple2 Pulse.Syntax.Base.term\n (fun p -> Pulse.Typing.tot_typing g p Pulse.Typing.tm_prop))\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Checker.IntroPure\n\nopen Pulse.Syntax\nopen Pulse.Typing\nopen Pulse.Checker.Base\nopen Pulse.Checker.Prover\n\nmodule T = FStar.Tactics.V2\nmodule P = Pulse.Syntax.Printer\n\nPartial implementation:\nlet check_prop (g: env) (p: term) : T.Tac (p: term & tot_typing g p tm_prop) =\n \n"
},
{
"role": "assistant",
"content": "let p0 = p in\nlet (| p , p_typing |) = Pulse.Checker.Pure.check_vprop g (tm_pure p) in\nmatch p.t with\n| Tm_Pure pp ->\n let prop_typing = Pulse.Typing.Metatheory.pure_typing_inversion #_ #pp p_typing in\n (| pp, prop_typing |)\n| _ ->\n fail g\n None\n (Printf.sprintf \"Impossible: check_intro_pure: checking a pure vprop %s returned a non-pure vprop %s,please file a bug-report\"\n (P.term_to_string (tm_pure p0))\n (P.term_to_string p))"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: abspat: a\n -> FStar.Tactics.Effect.Tac\n (FStar.Tactics.PatternMatching.matching_problem *\n FStar.Tactics.PatternMatching.abspat_continuation)\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n \nlet specialize_abspat_continuation' (continuation: abspat_continuation)\n (solution_term:term)\n : Tac term =\n let mk_arg_term argspec =\n abspat_arg_of_abspat_argspec solution_term argspec in\n let argspecs, body = continuation in\n hoist_and_apply body (map mk_arg_term argspecs) []\n\n(** Specialize a continuation of type ``abspat_continuation``. This yields a\nquoted function taking a matching solution and running its body with appropriate\nbindings. **)\nlet specialize_abspat_continuation (continuation: abspat_continuation)\n : Tac term =\n let solution_binder = fresh_binder (`matching_solution) in\n let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in\n let applied = specialize_abspat_continuation' continuation solution_term in\n let thunked = pack (Tv_Abs solution_binder applied) in\n debug (\"Specialized into \" ^ (term_to_string thunked));\n let normalized = beta_reduce thunked in\n debug (\"… which reduces to \" ^ (term_to_string normalized));\n thunked\n\n(** Interpret a continuation of type ``abspat_continuation``.\nThis yields a function taking a matching solution and running the body of the\ncontinuation with appropriate bindings. **)\nlet interp_abspat_continuation (a:Type0) (continuation: abspat_continuation)\n : Tac (matching_solution -> Tac a) =\n let applied = specialize_abspat_continuation continuation in\n unquote #(matching_solution -> Tac a) applied\n\n/// Putting it all together\n/// =======================\n///\n/// We now have all we need to use pattern-matching, short of a few convenience functions:\n\nPartial implementation:\nlet interp_abspat #a (abspat: a) : Tac (matching_problem * abspat_continuation) =\n \n"
},
{
"role": "assistant",
"content": "matching_problem_of_abs (quote abspat)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: _: FStar.Tactics.PatternMatching.pattern -> Prims.string\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nPartial implementation:\nlet rec string_of_pattern =\n \n"
},
{
"role": "assistant",
"content": "function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \" ^ string_of_pattern r ^ \")\""
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: d: Pulse.Typing.br_typing g sc_u sc_ty sc p e c -> Prims.Tot FStar.Stubs.Reflection.V2.Data.branch\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\n\nlet elab_bind #g #x #c1 #c2 #c\n (bc:bind_comp g x c1 c2 c)\n (e1 e2:R.term)\n : R.term\n = let t1 = elab_term (comp_res c1) in\n let t2 = elab_term (comp_res c2) in\n match c1 with\n | C_ST _ ->\n mk_bind_stt\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STGhost _ ->\n mk_bind_ghost\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in \n mk_bind_atomic\n (comp_u c1)\n (comp_u c2)\n (elab_observability obs1)\n (elab_observability obs2)\n (elab_term (comp_inames c1))\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n \nlet elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term)\n : Tot R.term\n = match d with\n | Lift_STAtomic_ST _ _ ->\n let t = elab_term (comp_res c1) in\n mk_lift_atomic_stt\n (comp_u c1)\n (elab_term (comp_res c1))\n t\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\n | Lift_Observability _ c o2 ->\n let t = elab_term (comp_res c1) in\n mk_lift_observability\n (comp_u c1)\n (elab_observability (C_STAtomic?.obs c))\n (elab_observability o2)\n (elab_term (comp_inames c1))\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n \n | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) ->\n let t = elab_term (comp_res c1) in\n mk_lift_ghost_neutral\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n (elab_term reveal_a)\n\n | Lift_Neutral_Ghost _ c ->\n let t = elab_term (comp_res c1) in\n mk_lift_neutral_ghost\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\nlet intro_pure_tm (p:term) =\n let open Pulse.Reflection.Util in\n wtag (Some STT_Ghost) \n (Tm_STApp\n { head =\n tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid \"intro_pure\")))\n None\n p;\n arg_qual = None;\n arg = tm_fstar (`()) Range.range_0 })\n\nlet simple_arr (t1 t2 : R.term) : R.term =\n let b = R.pack_binder {\n sort = t1;\n ppname = Sealed.seal \"x\";\n qual = R.Q_Explicit;\n attrs = [] } in\n R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))\n\nlet elab_st_sub (#g:env) (#c1 #c2 : comp)\n (d_sub : st_sub g c1 c2)\n : Tot (t:R.term\n & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2)))\n= RU.magic_s \"elab_st_sub\"\n\nPartial implementation:\nlet rec elab_br\n (#g: env)\n (#c: comp_st)\n (#sc_u: universe)\n (#sc_ty: typ)\n (#sc: term)\n (#p: pattern)\n (#e: st_term)\n (d: br_typing g sc_u sc_ty sc p e c)\n : Tot R.branch (decreases d) =\n \n"
},
{
"role": "assistant",
"content": "let TBR _ _ _ _ _ _ _ _ bs _ _ _ ed = d in\nlet e = elab_st_typing ed in\n(elab_pat p, e)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: f: (_: a -> FStar.Tactics.PatternMatching.match_res b) -> aa: a -> FStar.Tactics.Effect.Tac b\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nPartial implementation:\nlet lift_exn_tac #a #b (f: (a -> match_res b)) (aa: a) : Tac b =\n \n"
},
{
"role": "assistant",
"content": "match f aa with\n| Success bb -> bb\n| Failure ex -> Tactics.fail (string_of_match_exception ex)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n abspat: a ->\n k:\n (_: FStar.Tactics.PatternMatching.abspat_continuation\n -> FStar.Tactics.Effect.Tac\n (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac b))\n -> FStar.Tactics.Effect.Tac b\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\n(** Retrieve the function used to locate a value for a given abspat binder. **)\nlet locate_fn_of_binder_kind binder_kind =\n match binder_kind with\n | ABKVar _ -> `ms_locate_var\n | ABKHyp -> `ms_locate_hyp\n | ABKGoal -> `ms_locate_unit\n\n(** Construct a term fetching the value of an abspat argument from a quoted\nmatching solution ``solution_term``. **)\nlet abspat_arg_of_abspat_argspec solution_term (argspec: abspat_argspec)\n : Tac term =\n let loc_fn = locate_fn_of_binder_kind argspec.asa_kind in\n let name_tm = pack (Tv_Const (C_String (unseal argspec.asa_name.ppname))) in\n let locate_args = [(arg_type_of_binder_kind argspec.asa_kind, Q_Explicit);\n (solution_term, Q_Explicit); (name_tm, Q_Explicit)] in\n mk_app loc_fn locate_args\n\n(** Specialize a continuation of type ``abspat_continuation``.\nThis constructs a fully applied version of `continuation`, but it requires a\nquoted solution to be passed in. **)\n\nlet rec hoist_and_apply (head:term) (arg_terms:list term) (hoisted_args:list argv)\n : Tac term =\n match arg_terms with\n | [] -> mk_app head (List.rev hoisted_args)\n | arg_term::rest ->\n let n = List.Tot.length hoisted_args in\n //let bv = fresh_bv_named (\"x\" ^ (string_of_int n)) in\n let nb : binder = {\n ppname = seal (\"x\" ^ string_of_int n);\n sort = pack Tv_Unknown;\n uniq = fresh ();\n qual = Q_Explicit;\n attrs = [] ;\n }\n in\n pack (Tv_Let false [] nb arg_term (hoist_and_apply head rest ((pack (Tv_Var (binder_to_namedv nb)), Q_Explicit)::hoisted_args)))\n \nlet specialize_abspat_continuation' (continuation: abspat_continuation)\n (solution_term:term)\n : Tac term =\n let mk_arg_term argspec =\n abspat_arg_of_abspat_argspec solution_term argspec in\n let argspecs, body = continuation in\n hoist_and_apply body (map mk_arg_term argspecs) []\n\n(** Specialize a continuation of type ``abspat_continuation``. This yields a\nquoted function taking a matching solution and running its body with appropriate\nbindings. **)\nlet specialize_abspat_continuation (continuation: abspat_continuation)\n : Tac term =\n let solution_binder = fresh_binder (`matching_solution) in\n let solution_term = pack (Tv_Var (binder_to_namedv solution_binder)) in\n let applied = specialize_abspat_continuation' continuation solution_term in\n let thunked = pack (Tv_Abs solution_binder applied) in\n debug (\"Specialized into \" ^ (term_to_string thunked));\n let normalized = beta_reduce thunked in\n debug (\"… which reduces to \" ^ (term_to_string normalized));\n thunked\n\n(** Interpret a continuation of type ``abspat_continuation``.\nThis yields a function taking a matching solution and running the body of the\ncontinuation with appropriate bindings. **)\nlet interp_abspat_continuation (a:Type0) (continuation: abspat_continuation)\n : Tac (matching_solution -> Tac a) =\n let applied = specialize_abspat_continuation continuation in\n unquote #(matching_solution -> Tac a) applied\n\n/// Putting it all together\n/// =======================\n///\n/// We now have all we need to use pattern-matching, short of a few convenience functions:\n\n(** Construct a matching problem from an abspat. **)\nlet interp_abspat #a (abspat: a)\n : Tac (matching_problem * abspat_continuation) =\n matching_problem_of_abs (quote abspat)\n\n(** Construct an solve a matching problem.\nThis higher-order function isn't very usable on its own — it's mostly a\n\nPartial implementation:\nlet match_abspat #b #a (abspat: a) (k: (abspat_continuation -> Tac (matching_solution -> Tac b)))\n : Tac b =\n \n"
},
{
"role": "assistant",
"content": "let goal = cur_goal () in\nlet hypotheses = vars_of_env (cur_env ()) in\nlet problem, continuation = interp_abspat abspat in\nsolve_mp problem hypotheses goal (k continuation)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: t: (_: Prims.unit -> FStar.Tactics.Effect.Tac a) -> message: Prims.string\n -> FStar.Tactics.Effect.Tac Prims.unit\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\nPartial implementation:\nlet mustfail #a (t: (unit -> Tac a)) (message: string) : Tac unit =\n \n"
},
{
"role": "assistant",
"content": "match trytac t with\n| Some _ -> fail message\n| None -> ()"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: _: FStar.Tactics.PatternMatching.match_exception -> FStar.Tactics.Effect.Tac Prims.string\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nPartial implementation:\nlet string_of_match_exception =\n \n"
},
{
"role": "assistant",
"content": "function\n| NameMismatch (qn1, qn2) -> \"Match failure (name mismatch): expecting \" ^ qn1 ^ \", found \" ^ qn2\n| SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^ desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n| NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^\n nm ^ \" needs to match both \" ^ (term_to_string t1) ^ \" and \" ^ (term_to_string t2)\n| UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^ term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n| IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp \\226\\128\\166``, or ``goal \\226\\128\\166``)\""
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n p: MerkleTree.Spec.path n ->\n idx: Prims.nat{idx < Prims.pow2 n} ->\n h: MerkleTree.Spec.padded_hash ->\n rt: MerkleTree.Spec.padded_hash\n -> Prims.GTot Prims.prop\nEffect: Prims.GTot\n\nContext:\nmodule MerkleTree.Spec\n\nopen FStar.Classical\nopen FStar.Mul\nopen FStar.Seq\n\nmodule S = FStar.Seq\n\n#set-options \"--max_fuel 0 --max_ifuel 0 --z3rlimit 10\"\n\n// For SHA2_256, this is is a sequence of 32 bytes\n// These are secret bytes, hence not an eqtype\ntype hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz }\n\ntype hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz)\n\nval sha256_compress: hash_fun_t #32\nlet sha256_compress src1 src2 =\n let sz = Spec.Hash.Definitions.SHA2_256 in\n let hash_alg = Spec.Hash.Definitions.SHA2_256 in\n let acc = Spec.Agile.Hash.init hash_alg in\n let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in\n Spec.Agile.Hash.finish hash_alg acc ()\n\n/// For simplicity, we will specify the root for a sequence of [i]\n/// tags where [i <= 2^n] as the root of a full binary tree with [2^n]\n/// leaves obtained by padding the sequence with dummies. This\n/// requires extending the definitions of hashes and hash functions. Our\n/// extended definition of hash justifies skipping any concrete\n/// computation on dummies.\nnoeq\ntype padded_hash #hsz =\n| HRaw: hr:hash #hsz -> padded_hash #hsz\n| HPad // right padding to make the size of a Merkle tree a power of 2\n\nval padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)\nlet padded_hash_fun #hsz f lh rh =\n allow_inversion (padded_hash #hsz);\n match lh, rh with\n | HPad , _ -> HPad\n | _ , HPad -> lh\n | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)\n\nnoextract\nval hashes (#hsz:pos): Type0\nlet hashes #hsz = S.seq (padded_hash #hsz)\n\ntype merkle_tree (#hsz:pos) n = hs:hashes #hsz {S.length hs = pow2 n}\n\nval mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz)\nlet mt_get #_ #_ mt idx = S.index mt idx\n\nunfold let op_String_Access (#hsz:pos) = S.index #(padded_hash #hsz)\n\n#push-options \"--max_fuel 1\"\n\nval mt_left: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)\nlet mt_left #_ #n mt = S.slice mt 0 (pow2 (n-1))\n\nval mt_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)\nlet mt_right #_ #n mt = S.slice mt (pow2 (n-1)) (pow2 n)\n\nval mt_left_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n ->\n Lemma (S.equal mt (mt_left mt @| mt_right mt))\nlet mt_left_right #_ #_ mt = ()\n\nval 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})\nlet rec hs_next_lv #hsz #f #n hs =\n if n = 0 then S.empty\n else S.cons\n (padded_hash_fun #hsz f hs.[0] hs.[1])\n (hs_next_lv #hsz #f #(n-1) (S.slice hs 2 (S.length hs)))\n\nval hs_next_lv_index: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes{S.length hs = 2 * n} -> i:nat{i < n} ->\n Lemma ((hs_next_lv #hsz #f #n hs).[i] == padded_hash_fun #hsz f hs.[2 * i] hs.[2 * i + 1])\nlet rec hs_next_lv_index #hsz #f #n hs i =\n if n = 0 || i = 0 then ()\n else hs_next_lv_index #hsz #f #(n - 1) (S.slice hs 2 (S.length hs)) (i - 1)\n\nval hs_next_lv_slice:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->\n hs:hashes{S.length hs = 2 * n} -> i:nat -> j:nat{i <= j && j <= n} ->\n Lemma (requires True)\n (ensures S.equal (hs_next_lv #hsz #f #(j - i) (S.slice hs (2 * i) (2 * j)))\n (S.slice (hs_next_lv #hsz #f #n hs) i j))\n (decreases (j - i))\nlet rec hs_next_lv_slice #hsz #f #n hs i j =\n if i = j then ()\n else begin\n let x = S.slice hs (2 * i) (2 * j) in\n assert (S.equal (hs_next_lv #hsz #f #(j - i) x)\n (S.cons (padded_hash_fun #hsz f x.[0] x.[1])\n (hs_next_lv #hsz #f #(j - i - 1) (S.slice x 2 (S.length x)))));\n hs_next_lv_slice #hsz #f #n hs (i + 1) j;\n hs_next_lv_index #hsz #f #n hs i\n end\n\nval mt_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> GTot (merkle_tree #hsz (n-1))\nlet mt_next_lv #_ #f #n mt = hs_next_lv #_ #f #(pow2 (n-1)) mt\n\nval mt_next_lv_mt_left: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n ->\n Lemma (S.equal (mt_next_lv #_ #f #_ (mt_left mt)) (mt_left (mt_next_lv #_ #f #_ mt)))\nlet mt_next_lv_mt_left #hsz #f #n mt =\n hs_next_lv_slice #_ #f #(pow2 (n-1)) mt 0 (pow2 (n-2))\n\nval mt_next_lv_mt_right: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n ->\n Lemma (S.equal (mt_next_lv #_ #f #_ (mt_right mt)) (mt_right (mt_next_lv #_ #f #_ mt)))\nlet mt_next_lv_mt_right #hsz #f #n mt =\n hs_next_lv_slice #hsz #f #(pow2 (n-1)) mt (pow2 (n-2)) (pow2 (n-1))\n\nval hs_next_lv_equiv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n j:nat -> n:pos{j <= 2 * n} ->\n hs1:hashes{S.length hs1 = 2 * n} ->\n hs2:hashes{S.length hs2 = 2 * n} ->\n Lemma (requires S.equal (S.slice hs1 0 j) (S.slice hs2 0 j))\n (ensures S.equal (S.slice (hs_next_lv #hsz #f #n hs1) 0 (j / 2))\n (S.slice (hs_next_lv #hsz #f #n hs2) 0 (j / 2)))\nlet hs_next_lv_equiv #hsz #f j n hs1 hs2 =\n forall_intro (hs_next_lv_index #_ #f #n hs1);\n forall_intro (hs_next_lv_index #_ #f #n hs2);\n let hs1' = hs_next_lv #_ #f #n hs1 in\n let hs2' = hs_next_lv #_ #f #n hs2 in\n assert (forall (i:nat{i < j / 2}). hs1'.[i] == padded_hash_fun #hsz f hs1.[2 * i] hs1.[2 * i + 1]);\n assert (forall (i:nat{i < j / 2}). hs2'.[i] == padded_hash_fun #hsz f hs2.[2 * i] hs2.[2 * i + 1]);\n assert (forall (i:nat{i < j}). (S.slice hs1 0 j).[i] == (S.slice hs2 0 j).[i]);\n assert (forall (i:nat{i < j}). hs1.[i] == hs2.[i]);\n assert (forall (i:nat{i < j / 2}). hs1.[2 * i] == hs2.[2 * i]);\n assert (forall (i:nat{i < j / 2}). hs1.[2 * i + 1] == hs2.[2 * i + 1]);\n assert (forall (i:nat{i < j / 2}). hs1'.[i] == hs2'.[i])\n\nval mt_next_lv_equiv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n j:nat -> n:pos{j <= pow2 n} ->\n mt1:merkle_tree #hsz n -> mt2:merkle_tree #hsz n ->\n Lemma (requires S.equal (S.slice mt1 0 j) (S.slice mt2 0 j))\n (ensures S.equal (S.slice (mt_next_lv #_ #f #_ mt1) 0 (j / 2))\n (S.slice (mt_next_lv #_ #f #_ mt2) 0 (j / 2)))\nlet mt_next_lv_equiv #hsz #f j n mt1 mt2 =\n hs_next_lv_equiv #_ #f j (pow2 (n-1)) mt1 mt2\n\nval hs_next_rel:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:nat ->\n hs:hashes #hsz {S.length hs = 2 * n} ->\n nhs:hashes #hsz {S.length nhs = n} ->\n GTot Type0\nlet hs_next_rel #hsz #f n hs nhs =\n forall (i:nat{i < n}).\n S.index nhs i ==\n padded_hash_fun #hsz f (S.index hs (2 * i)) (S.index hs (2 * i + 1))\n\nval mt_next_rel:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree #hsz (n - 1) ->\n GTot Type0\nlet mt_next_rel #hsz #f n mt nmt =\n hs_next_rel #hsz #f (pow2 (n-1)) mt nmt\n\nval hs_next_rel_next_lv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:nat ->\n hs:hashes{S.length hs = 2 * n} ->\n nhs:hashes{S.length nhs = n} ->\n Lemma (requires hs_next_rel #_ #f n hs nhs)\n (ensures S.equal nhs (hs_next_lv #_ #f #n hs))\nlet rec hs_next_rel_next_lv #hsz #f n hs nhs =\n if n = 0 then ()\n else hs_next_rel_next_lv #_ #f (n - 1)\n (S.slice hs 2 (S.length hs))\n (S.slice nhs 1 (S.length nhs))\n\nval mt_next_rel_next_lv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree (n - 1) ->\n Lemma (requires mt_next_rel #_ #f n mt nmt)\n (ensures S.equal nmt (mt_next_lv #_ #f mt))\nlet mt_next_rel_next_lv #hsz #f n mt nmt =\n hs_next_rel_next_lv #_ #f (pow2 (n-1)) mt nmt\n\nval mt_next_rel_upd_even:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree (n - 1) ->\n i:nat{i < pow2 (n-1)} ->\n v:padded_hash ->\n Lemma (requires mt_next_rel #_ #f n mt nmt)\n (ensures mt_next_rel #_ #f n\n (S.upd mt (2 * i) v)\n (S.upd nmt i (padded_hash_fun #hsz f v (S.index mt (2 * i + 1)))))\nlet mt_next_rel_upd_even #hsz #f n mt nmt i v = ()\n\n#push-options \"--z3rlimit 10 --initial_fuel 1 --max_fuel 1 --initial_ifuel 1 --max_ifuel 1\"\nval mt_next_rel_upd_even_pad:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree #hsz (n - 1) ->\n i:nat{i < pow2 (n-1)} ->\n v:padded_hash #hsz ->\n Lemma (requires (mt_next_rel #_ #f n mt nmt) /\\ (S.index mt (2 * i + 1) == HPad))\n (ensures (mt_next_rel #_ #f n (S.upd mt (2 * i) v) (S.upd nmt i v)))\nlet mt_next_rel_upd_even_pad #hsz #f n mt nmt i v = ()\n#pop-options\n\nval mt_next_rel_upd_odd:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree (n - 1) ->\n i:nat{i < pow2 (n-1)} ->\n v:padded_hash ->\n Lemma (requires mt_next_rel #_ #f n mt nmt)\n (ensures mt_next_rel #_ #f n\n (S.upd mt (2 * i + 1) v)\n (S.upd nmt i (padded_hash_fun #_ f (S.index mt (2 * i)) v)))\nlet mt_next_rel_upd_odd #hsz #f n mt nmt i v = ()\n\n// fournet: just [root]?\nval mt_get_root:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n #n:nat -> mt:merkle_tree #hsz n -> GTot (padded_hash #hsz)\nlet rec mt_get_root #hsz #f #n mt =\n if n = 0 then mt.[0]\n else mt_get_root #_ #f (mt_next_lv #_ #f mt)\n\n#push-options \"--initial_fuel 2 --max_fuel 2\"\n\nval mt_get_root_step: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n ->\n Lemma (mt_get_root #_ #f mt ==\n padded_hash_fun #_ f (mt_get_root #_ #f (mt_left mt)) (mt_get_root #_ #f (mt_right mt)))\nlet rec mt_get_root_step #hsz #f #n mt =\n if n = 1 then ()\n else begin\n mt_get_root_step #_ #f (mt_next_lv #_ #f mt);\n mt_next_lv_mt_left #_ #f mt;\n mt_next_lv_mt_right #_ #f mt\n end\n\n#pop-options\n\ntype path #hsz n = S.lseq (padded_hash #hsz) n\n\n/// We first specify full paths, including padding.\n\nval mt_get_path:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->\n mt:merkle_tree #hsz n -> i:nat{i < pow2 n} -> GTot (path #hsz n)\nlet rec mt_get_path #hsz #f #n t i =\n if n = 0 then S.empty\n else S.cons\n (if i % 2 = 0 then t.[i + 1] else t.[i - 1])\n (mt_get_path #_ #f (mt_next_lv #_ #f t) (i / 2))\n\nval mt_verify_:\n #hsz:pos -> #f:hash_fun_t #hsz ->#n:nat ->\n p:path #hsz n -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> GTot (padded_hash #hsz)\nlet rec mt_verify_ #hsz #f #n p idx h =\n if n = 0 then h\n else mt_verify_ #_ #f #(n-1) (S.tail p) (idx / 2)\n (if idx % 2 = 0\n then padded_hash_fun #_ f h (S.head p)\n else padded_hash_fun #_ f (S.head p) h)\n\nval mt_verify:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->\n\nPartial implementation:\nlet mt_verify #hsz #f #n p idx h rt =\n \n"
},
{
"role": "assistant",
"content": "rt == mt_verify_ #_ #f p idx h"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: _: Prims.unit\n -> FStar.Tactics.Effect.Tac (FStar.Tactics.NamedView.term * FStar.Tactics.NamedView.term)\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nPartial implementation:\nlet fetch_eq_side () : Tac (term * term) =\n \n"
},
{
"role": "assistant",
"content": "let g = cur_goal () in\nmatch inspect g with\n| Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn\n then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn\n then (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n| _ -> fail \"not an app at top level\""
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: mp: FStar.Tactics.PatternMatching.matching_problem -> Prims.string\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nPartial implementation:\nlet string_of_matching_problem mp =\n \n"
},
{
"role": "assistant",
"content": "let vars = String.concat \", \" mp.mp_vars in\nlet hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) -> nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps)\nin\nlet goal =\n match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat\nin\n\"\\n{ vars: \" ^ vars ^ \"\\n\" ^ \" hyps: \" ^ hyps ^ \"\\n\" ^ \" goal: \" ^ goal ^ \" }\""
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: f: (_: a -> FStar.Tactics.PatternMatching.match_res b) -> aa: a -> FStar.Tactics.Effect.Tac b\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nPartial implementation:\nlet lift_exn_tactic #a #b (f: (a -> match_res b)) (aa: a) : Tac b =\n \n"
},
{
"role": "assistant",
"content": "match f aa with\n| Success bb -> bb\n| Failure ex -> Tactics.fail (string_of_match_exception ex)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: d: Pulse.Typing.st_typing g t c -> Prims.Tot FStar.Stubs.Reflection.Types.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\n\nlet elab_bind #g #x #c1 #c2 #c\n (bc:bind_comp g x c1 c2 c)\n (e1 e2:R.term)\n : R.term\n = let t1 = elab_term (comp_res c1) in\n let t2 = elab_term (comp_res c2) in\n match c1 with\n | C_ST _ ->\n mk_bind_stt\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STGhost _ ->\n mk_bind_ghost\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in \n mk_bind_atomic\n (comp_u c1)\n (comp_u c2)\n (elab_observability obs1)\n (elab_observability obs2)\n (elab_term (comp_inames c1))\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n \nlet elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term)\n : Tot R.term\n = match d with\n | Lift_STAtomic_ST _ _ ->\n let t = elab_term (comp_res c1) in\n mk_lift_atomic_stt\n (comp_u c1)\n (elab_term (comp_res c1))\n t\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\n | Lift_Observability _ c o2 ->\n let t = elab_term (comp_res c1) in\n mk_lift_observability\n (comp_u c1)\n (elab_observability (C_STAtomic?.obs c))\n (elab_observability o2)\n (elab_term (comp_inames c1))\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n \n | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) ->\n let t = elab_term (comp_res c1) in\n mk_lift_ghost_neutral\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n (elab_term reveal_a)\n\n | Lift_Neutral_Ghost _ c ->\n let t = elab_term (comp_res c1) in\n mk_lift_neutral_ghost\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\nlet intro_pure_tm (p:term) =\n let open Pulse.Reflection.Util in\n wtag (Some STT_Ghost) \n (Tm_STApp\n { head =\n tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid \"intro_pure\")))\n None\n p;\n arg_qual = None;\n arg = tm_fstar (`()) Range.range_0 })\n\nlet simple_arr (t1 t2 : R.term) : R.term =\n let b = R.pack_binder {\n sort = t1;\n ppname = Sealed.seal \"x\";\n qual = R.Q_Explicit;\n attrs = [] } in\n R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))\n\nlet elab_st_sub (#g:env) (#c1 #c2 : comp)\n (d_sub : st_sub g c1 c2)\n : Tot (t:R.term\n & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2)))\n= RU.magic_s \"elab_st_sub\"\n\nPartial implementation:\nlet rec elab_st_typing (#g: env) (#t: st_term) (#c: comp) (d: st_typing g t c)\n : Tot R.term (decreases d) =\n \n"
},
{
"role": "assistant",
"content": "match d with\n| T_Abs _ x qual b _u body _c ty_typing body_typing ->\n let ty = elab_term b.binder_ty in\n let ppname = b.binder_ppname.name in\n let body = elab_st_typing body_typing in\n mk_abs_with_name ppname ty (elab_qual qual) (RT.close_term body x)\n| T_STApp _ head _ qual _ arg _ _\n| T_STGhostApp _ head _ qual _ arg _ _ _ _ ->\n let head = elab_term head in\n let arg = elab_term arg in\n R.mk_app head [(arg, elab_qual qual)]\n| T_Return _ c use_eq u ty t post _ _ _ _ ->\n let ru = u in\n let rty = elab_term ty in\n let rt = elab_term t in\n let rp = elab_term post in\n let rp = mk_abs rty R.Q_Explicit rp in\n (match c, use_eq with\n | STT, true -> mk_stt_return ru rty rt rp\n | STT, false -> mk_stt_return_noeq ru rty rt rp\n | STT_Atomic, true -> mk_stt_atomic_return ru rty rt rp\n | STT_Atomic, false -> mk_stt_atomic_return_noeq ru rty rt rp\n | STT_Ghost, true -> mk_stt_ghost_return ru rty rt rp\n | STT_Ghost, false -> mk_stt_ghost_return_noeq ru rty rt rp)\n| T_Bind _ e1 e2 c1 c2 b x c e1_typing t_typing e2_typing bc ->\n let e1 = elab_st_typing e1_typing in\n let e2 = elab_st_typing e2_typing in\n let ty1 = elab_term (comp_res c1) in\n elab_bind bc e1 (mk_abs_with_name b.binder_ppname.name ty1 R.Q_Explicit (RT.close_term e2 x))\n| T_BindFn _ _ _ c1 c2 b x e1_typing _u t_typing e2_typing c2_typing ->\n let e1 = elab_st_typing e1_typing in\n let e2 = elab_st_typing e2_typing in\n let ty1 = elab_term (comp_res c1) in\n RT.mk_let RT.pp_name_default e1 ty1 (RT.close_term e2 x)\n| T_Frame _ _ c frame _frame_typing e_typing ->\n let e = elab_st_typing e_typing in\n elab_frame c frame e\n| T_Equiv _ _ c1 c2 e_typing (ST_TotEquiv _ _ _ _ _ _) ->\n let e = elab_st_typing e_typing in\n e\n| T_Equiv _ _ c1 c2 e_typing _ ->\n let e = elab_st_typing e_typing in\n elab_sub c1 c2 e\n| T_Sub _ _ c1 c2 e_typing d_sub ->\n let e = elab_st_typing e_typing in\n let (| coercion , _ |) = elab_st_sub d_sub in\n R.mk_e_app coercion [e]\n| T_Lift _ _ c1 c2 e_typing lc ->\n let e = elab_st_typing e_typing in\n elab_lift lc e\n| T_If _ b _ _ _ _ _ e1_typing e2_typing _c_typing ->\n let rb = elab_term b in\n let re1 = elab_st_typing e1_typing in\n let re2 = elab_st_typing e2_typing in\n RT.mk_if rb re1 re2\n| T_Match _ _ _ sc _ _ _ _ _ brty _ ->\n let sc = elab_term sc in\n let brs = elab_branches brty in\n R.pack_ln (R.Tv_Match sc None brs)\n| T_IntroPure _ p _ _ ->\n let head = tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid \"intro_pure\"))) None p in\n let arg = (`()) in\n R.mk_app (elab_term head) [(arg, elab_qual None)]\n| T_ElimExists _ u t p _ d_t d_exists ->\n let ru = u in\n let rt = elab_term t in\n let rp = elab_term p in\n mk_elim_exists ru rt (mk_abs rt R.Q_Explicit rp)\n| T_IntroExists _ u b p e _ _ _ ->\n let ru = u in\n let rt = elab_term b.binder_ty in\n let rp = elab_term p in\n let re = elab_term e in\n mk_intro_exists ru rt (mk_abs rt R.Q_Explicit rp) re\n| T_While _ inv _ _ _ cond_typing body_typing ->\n let inv = elab_term inv in\n let cond = elab_st_typing cond_typing in\n let body = elab_st_typing body_typing in\n mk_while (mk_abs bool_tm R.Q_Explicit inv) cond body\n| T_Par _ eL cL eR cR _ _ _ eL_typing eR_typing ->\n let ru = comp_u cL in\n let raL = elab_term (comp_res cL) in\n let raR = elab_term (comp_res cR) in\n let rpreL = elab_term (comp_pre cL) in\n let rpostL = elab_term (comp_post cL) in\n let rpreR = elab_term (comp_pre cR) in\n let rpostR = elab_term (comp_post cR) in\n let reL = elab_st_typing eL_typing in\n let reR = elab_st_typing eR_typing in\n mk_par ru\n raL\n raR\n rpreL\n (mk_abs raL R.Q_Explicit rpostL)\n rpreR\n (mk_abs raR R.Q_Explicit rpostR)\n reL\n reR\n| T_Rewrite _ p q _ _ ->\n let rp = elab_term p in\n let rq = elab_term q in\n mk_rewrite rp rq\n| T_WithLocal _ _ init _ init_t c x _ _ _ body_typing ->\n let rret_u = comp_u c in\n let ra = elab_term init_t in\n let rinit = elab_term init in\n let rret_t = elab_term (comp_res c) in\n let rpre = elab_term (comp_pre c) in\n let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in\n let rbody = elab_st_typing body_typing in\n let rbody = RT.close_term rbody x in\n let rbody = mk_abs (mk_ref ra) R.Q_Explicit rbody in\n mk_withlocal rret_u ra rinit rpre rret_t rpost rbody\n| T_WithLocalArray _ _ init len _ init_t c x _ _ _ _ body_typing ->\n let rret_u = comp_u c in\n let ra = elab_term init_t in\n let rinit = elab_term init in\n let rlen = elab_term len in\n let rret_t = elab_term (comp_res c) in\n let rpre = elab_term (comp_pre c) in\n let rpost = mk_abs rret_t R.Q_Explicit (elab_term (comp_post c)) in\n let rbody = elab_st_typing body_typing in\n let rbody = RT.close_term rbody x in\n let rbody = mk_abs (mk_array ra) R.Q_Explicit rbody in\n mk_withlocalarray rret_u ra rinit rlen rpre rret_t rpost rbody\n| T_Admit _ { u = u ; res = res ; pre = pre ; post = post } c _ ->\n let ru = u in\n let rres = elab_term res in\n let rpre = elab_term pre in\n let rpost = elab_term post in\n let rpost = mk_abs rres R.Q_Explicit rpost in\n (match c with\n | STT -> mk_stt_admit ru rres rpre rpost\n | STT_Atomic -> mk_stt_atomic_admit ru rres rpre rpost\n | STT_Ghost -> mk_stt_ghost_admit ru rres rpre rpost)\n| T_Unreachable _ _ _ _ _ -> `(\"IOU: elab_st_typing of T_Unreachable\")\n| T_WithInv _ _ _ _ _ _ _ _ _ -> `(\"IOU: elab_st_typing of T_WithInv\")"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: d: Pulse.Typing.brs_typing g sc_u sc_ty sc brs c\n -> Prims.Tot (Prims.list FStar.Stubs.Reflection.V2.Data.branch)\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2023 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n\nmodule Pulse.Elaborate.Core\nmodule RT = FStar.Reflection.Typing\nmodule R = FStar.Reflection.V2\nmodule L = FStar.List.Tot\nmodule T = FStar.Tactics.V2\nopen FStar.List.Tot\nopen Pulse.Syntax\nopen Pulse.Elaborate.Pure\nopen Pulse.Typing\nmodule RU = Pulse.RuntimeUtils\nopen Pulse.Reflection.Util\n\nlet elab_frame (c:comp_st) (frame:term) (e:R.term) =\n let u = comp_u c in\n let ty = elab_term (comp_res c) in\n let pre = elab_term (comp_pre c) in\n let post = elab_term (comp_post c) in\n if C_ST? c\n then mk_frame_stt u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else if C_STAtomic? c\n then let opened = elab_term (comp_inames c) in \n mk_frame_stt_atomic u ty opened pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n else mk_frame_stt_ghost u ty pre (mk_abs ty R.Q_Explicit post) (elab_term frame) e\n\nlet elab_sub (c1 c2:comp_st) (e:R.term) =\n let ty = elab_term (comp_res c1) in\n let u = comp_u c1 in\n let pre1 = elab_term (comp_pre c1) in\n let pre2 = elab_term (comp_pre c2) in\n let post1 = mk_abs ty R.Q_Explicit (elab_term (comp_post c1)) in\n let post2 = mk_abs ty R.Q_Explicit (elab_term (comp_post c2)) in\n if C_ST? c1\n then mk_sub_stt u ty pre1 pre2 post1 post2 e\n else if C_STAtomic? c1\n then let opened = elab_term (comp_inames c1) in\n mk_sub_stt_atomic u ty opened pre1 pre2 post1 post2 e\n else mk_sub_stt_ghost u ty pre1 pre2 post1 post2 e\n\n\nlet elab_bind #g #x #c1 #c2 #c\n (bc:bind_comp g x c1 c2 c)\n (e1 e2:R.term)\n : R.term\n = let t1 = elab_term (comp_res c1) in\n let t2 = elab_term (comp_res c2) in\n match c1 with\n | C_ST _ ->\n mk_bind_stt\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STGhost _ ->\n mk_bind_ghost\n (comp_u c1)\n (comp_u c2)\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n | C_STAtomic inames obs1 _ ->\n let C_STAtomic _ obs2 _ = c2 in \n mk_bind_atomic\n (comp_u c1)\n (comp_u c2)\n (elab_observability obs1)\n (elab_observability obs2)\n (elab_term (comp_inames c1))\n t1 t2\n (elab_term (comp_pre c1))\n (mk_abs t1 R.Q_Explicit (elab_term (comp_post c1)))\n (mk_abs t2 R.Q_Explicit (elab_term (comp_post c2)))\n e1 e2\n \nlet elab_lift #g #c1 #c2 (d:lift_comp g c1 c2) (e:R.term)\n : Tot R.term\n = match d with\n | Lift_STAtomic_ST _ _ ->\n let t = elab_term (comp_res c1) in\n mk_lift_atomic_stt\n (comp_u c1)\n (elab_term (comp_res c1))\n t\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\n | Lift_Observability _ c o2 ->\n let t = elab_term (comp_res c1) in\n mk_lift_observability\n (comp_u c1)\n (elab_observability (C_STAtomic?.obs c))\n (elab_observability o2)\n (elab_term (comp_inames c1))\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n \n | Lift_Ghost_Neutral _ _ (| reveal_a, reveal_a_typing |) ->\n let t = elab_term (comp_res c1) in\n mk_lift_ghost_neutral\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n (elab_term reveal_a)\n\n | Lift_Neutral_Ghost _ c ->\n let t = elab_term (comp_res c1) in\n mk_lift_neutral_ghost\n (comp_u c1)\n t\n (elab_term (comp_pre c1))\n (mk_abs t R.Q_Explicit (elab_term (comp_post c1)))\n e\n\nlet intro_pure_tm (p:term) =\n let open Pulse.Reflection.Util in\n wtag (Some STT_Ghost) \n (Tm_STApp\n { head =\n tm_pureapp (tm_fvar (as_fv (mk_pulse_lib_core_lid \"intro_pure\")))\n None\n p;\n arg_qual = None;\n arg = tm_fstar (`()) Range.range_0 })\n\nlet simple_arr (t1 t2 : R.term) : R.term =\n let b = R.pack_binder {\n sort = t1;\n ppname = Sealed.seal \"x\";\n qual = R.Q_Explicit;\n attrs = [] } in\n R.pack_ln (R.Tv_Arrow b (R.pack_comp (R.C_Total t2)))\n\nlet elab_st_sub (#g:env) (#c1 #c2 : comp)\n (d_sub : st_sub g c1 c2)\n : Tot (t:R.term\n & RT.tot_typing (elab_env g) t (simple_arr (elab_comp c1) (elab_comp c2)))\n= RU.magic_s \"elab_st_sub\"\n\nPartial implementation:\nlet rec elab_branches\n (#g: env)\n (#c: comp_st)\n (#sc_u: universe)\n (#sc_ty: typ)\n (#sc: term)\n (#brs: list branch)\n (d: brs_typing g sc_u sc_ty sc brs c)\n : Tot (list R.branch) (decreases d) =\n \n"
},
{
"role": "assistant",
"content": "match d with\n| TBRS_0 _ -> []\n| TBRS_1 _ p e bd _ d' -> elab_br bd :: elab_branches d'"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: hs: MerkleTree.Spec.hashes -> Type0\nEffect: Prims.Tot\n\nContext:\nmodule MerkleTree.Spec\n\nopen FStar.Classical\nopen FStar.Mul\nopen FStar.Seq\n\nmodule S = FStar.Seq\n\n#set-options \"--max_fuel 0 --max_ifuel 0 --z3rlimit 10\"\n\n// For SHA2_256, this is is a sequence of 32 bytes\n// These are secret bytes, hence not an eqtype\ntype hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz }\n\ntype hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz)\n\nval sha256_compress: hash_fun_t #32\nlet sha256_compress src1 src2 =\n let sz = Spec.Hash.Definitions.SHA2_256 in\n let hash_alg = Spec.Hash.Definitions.SHA2_256 in\n let acc = Spec.Agile.Hash.init hash_alg in\n let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in\n Spec.Agile.Hash.finish hash_alg acc ()\n\n/// For simplicity, we will specify the root for a sequence of [i]\n/// tags where [i <= 2^n] as the root of a full binary tree with [2^n]\n/// leaves obtained by padding the sequence with dummies. This\n/// requires extending the definitions of hashes and hash functions. Our\n/// extended definition of hash justifies skipping any concrete\n/// computation on dummies.\nnoeq\ntype padded_hash #hsz =\n| HRaw: hr:hash #hsz -> padded_hash #hsz\n| HPad // right padding to make the size of a Merkle tree a power of 2\n\nval padded_hash_fun: (#hsz:pos) -> (f:hash_fun_t #hsz) -> (lh:padded_hash #hsz) -> (rh:padded_hash #hsz) -> GTot (padded_hash #hsz)\nlet padded_hash_fun #hsz f lh rh =\n allow_inversion (padded_hash #hsz);\n match lh, rh with\n | HPad , _ -> HPad\n | _ , HPad -> lh\n | HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)\n\nnoextract\nval hashes (#hsz:pos): Type0\nlet hashes #hsz = S.seq (padded_hash #hsz)\n\ntype merkle_tree (#hsz:pos) n = hs:hashes #hsz {S.length hs = pow2 n}\n\nval mt_get: #hsz:pos -> #n:nat -> mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} -> GTot (padded_hash #hsz)\nlet mt_get #_ #_ mt idx = S.index mt idx\n\nunfold let op_String_Access (#hsz:pos) = S.index #(padded_hash #hsz)\n\n#push-options \"--max_fuel 1\"\n\nval mt_left: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)\nlet mt_left #_ #n mt = S.slice mt 0 (pow2 (n-1))\n\nval mt_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n -> merkle_tree #hsz (n-1)\nlet mt_right #_ #n mt = S.slice mt (pow2 (n-1)) (pow2 n)\n\nval mt_left_right: #hsz:pos -> #n:pos -> mt:merkle_tree #hsz n ->\n Lemma (S.equal mt (mt_left mt @| mt_right mt))\nlet mt_left_right #_ #_ mt = ()\n\nval 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})\nlet rec hs_next_lv #hsz #f #n hs =\n if n = 0 then S.empty\n else S.cons\n (padded_hash_fun #hsz f hs.[0] hs.[1])\n (hs_next_lv #hsz #f #(n-1) (S.slice hs 2 (S.length hs)))\n\nval hs_next_lv_index: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat -> hs:hashes{S.length hs = 2 * n} -> i:nat{i < n} ->\n Lemma ((hs_next_lv #hsz #f #n hs).[i] == padded_hash_fun #hsz f hs.[2 * i] hs.[2 * i + 1])\nlet rec hs_next_lv_index #hsz #f #n hs i =\n if n = 0 || i = 0 then ()\n else hs_next_lv_index #hsz #f #(n - 1) (S.slice hs 2 (S.length hs)) (i - 1)\n\nval hs_next_lv_slice:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->\n hs:hashes{S.length hs = 2 * n} -> i:nat -> j:nat{i <= j && j <= n} ->\n Lemma (requires True)\n (ensures S.equal (hs_next_lv #hsz #f #(j - i) (S.slice hs (2 * i) (2 * j)))\n (S.slice (hs_next_lv #hsz #f #n hs) i j))\n (decreases (j - i))\nlet rec hs_next_lv_slice #hsz #f #n hs i j =\n if i = j then ()\n else begin\n let x = S.slice hs (2 * i) (2 * j) in\n assert (S.equal (hs_next_lv #hsz #f #(j - i) x)\n (S.cons (padded_hash_fun #hsz f x.[0] x.[1])\n (hs_next_lv #hsz #f #(j - i - 1) (S.slice x 2 (S.length x)))));\n hs_next_lv_slice #hsz #f #n hs (i + 1) j;\n hs_next_lv_index #hsz #f #n hs i\n end\n\nval mt_next_lv: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n -> GTot (merkle_tree #hsz (n-1))\nlet mt_next_lv #_ #f #n mt = hs_next_lv #_ #f #(pow2 (n-1)) mt\n\nval mt_next_lv_mt_left: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n ->\n Lemma (S.equal (mt_next_lv #_ #f #_ (mt_left mt)) (mt_left (mt_next_lv #_ #f #_ mt)))\nlet mt_next_lv_mt_left #hsz #f #n mt =\n hs_next_lv_slice #_ #f #(pow2 (n-1)) mt 0 (pow2 (n-2))\n\nval mt_next_lv_mt_right: #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat{1 < n} -> mt:merkle_tree #hsz n ->\n Lemma (S.equal (mt_next_lv #_ #f #_ (mt_right mt)) (mt_right (mt_next_lv #_ #f #_ mt)))\nlet mt_next_lv_mt_right #hsz #f #n mt =\n hs_next_lv_slice #hsz #f #(pow2 (n-1)) mt (pow2 (n-2)) (pow2 (n-1))\n\nval hs_next_lv_equiv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n j:nat -> n:pos{j <= 2 * n} ->\n hs1:hashes{S.length hs1 = 2 * n} ->\n hs2:hashes{S.length hs2 = 2 * n} ->\n Lemma (requires S.equal (S.slice hs1 0 j) (S.slice hs2 0 j))\n (ensures S.equal (S.slice (hs_next_lv #hsz #f #n hs1) 0 (j / 2))\n (S.slice (hs_next_lv #hsz #f #n hs2) 0 (j / 2)))\nlet hs_next_lv_equiv #hsz #f j n hs1 hs2 =\n forall_intro (hs_next_lv_index #_ #f #n hs1);\n forall_intro (hs_next_lv_index #_ #f #n hs2);\n let hs1' = hs_next_lv #_ #f #n hs1 in\n let hs2' = hs_next_lv #_ #f #n hs2 in\n assert (forall (i:nat{i < j / 2}). hs1'.[i] == padded_hash_fun #hsz f hs1.[2 * i] hs1.[2 * i + 1]);\n assert (forall (i:nat{i < j / 2}). hs2'.[i] == padded_hash_fun #hsz f hs2.[2 * i] hs2.[2 * i + 1]);\n assert (forall (i:nat{i < j}). (S.slice hs1 0 j).[i] == (S.slice hs2 0 j).[i]);\n assert (forall (i:nat{i < j}). hs1.[i] == hs2.[i]);\n assert (forall (i:nat{i < j / 2}). hs1.[2 * i] == hs2.[2 * i]);\n assert (forall (i:nat{i < j / 2}). hs1.[2 * i + 1] == hs2.[2 * i + 1]);\n assert (forall (i:nat{i < j / 2}). hs1'.[i] == hs2'.[i])\n\nval mt_next_lv_equiv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n j:nat -> n:pos{j <= pow2 n} ->\n mt1:merkle_tree #hsz n -> mt2:merkle_tree #hsz n ->\n Lemma (requires S.equal (S.slice mt1 0 j) (S.slice mt2 0 j))\n (ensures S.equal (S.slice (mt_next_lv #_ #f #_ mt1) 0 (j / 2))\n (S.slice (mt_next_lv #_ #f #_ mt2) 0 (j / 2)))\nlet mt_next_lv_equiv #hsz #f j n mt1 mt2 =\n hs_next_lv_equiv #_ #f j (pow2 (n-1)) mt1 mt2\n\nval hs_next_rel:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:nat ->\n hs:hashes #hsz {S.length hs = 2 * n} ->\n nhs:hashes #hsz {S.length nhs = n} ->\n GTot Type0\nlet hs_next_rel #hsz #f n hs nhs =\n forall (i:nat{i < n}).\n S.index nhs i ==\n padded_hash_fun #hsz f (S.index hs (2 * i)) (S.index hs (2 * i + 1))\n\nval mt_next_rel:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree #hsz (n - 1) ->\n GTot Type0\nlet mt_next_rel #hsz #f n mt nmt =\n hs_next_rel #hsz #f (pow2 (n-1)) mt nmt\n\nval hs_next_rel_next_lv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:nat ->\n hs:hashes{S.length hs = 2 * n} ->\n nhs:hashes{S.length nhs = n} ->\n Lemma (requires hs_next_rel #_ #f n hs nhs)\n (ensures S.equal nhs (hs_next_lv #_ #f #n hs))\nlet rec hs_next_rel_next_lv #hsz #f n hs nhs =\n if n = 0 then ()\n else hs_next_rel_next_lv #_ #f (n - 1)\n (S.slice hs 2 (S.length hs))\n (S.slice nhs 1 (S.length nhs))\n\nval mt_next_rel_next_lv:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree (n - 1) ->\n Lemma (requires mt_next_rel #_ #f n mt nmt)\n (ensures S.equal nmt (mt_next_lv #_ #f mt))\nlet mt_next_rel_next_lv #hsz #f n mt nmt =\n hs_next_rel_next_lv #_ #f (pow2 (n-1)) mt nmt\n\nval mt_next_rel_upd_even:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree (n - 1) ->\n i:nat{i < pow2 (n-1)} ->\n v:padded_hash ->\n Lemma (requires mt_next_rel #_ #f n mt nmt)\n (ensures mt_next_rel #_ #f n\n (S.upd mt (2 * i) v)\n (S.upd nmt i (padded_hash_fun #hsz f v (S.index mt (2 * i + 1)))))\nlet mt_next_rel_upd_even #hsz #f n mt nmt i v = ()\n\n#push-options \"--z3rlimit 10 --initial_fuel 1 --max_fuel 1 --initial_ifuel 1 --max_ifuel 1\"\nval mt_next_rel_upd_even_pad:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree #hsz (n - 1) ->\n i:nat{i < pow2 (n-1)} ->\n v:padded_hash #hsz ->\n Lemma (requires (mt_next_rel #_ #f n mt nmt) /\\ (S.index mt (2 * i + 1) == HPad))\n (ensures (mt_next_rel #_ #f n (S.upd mt (2 * i) v) (S.upd nmt i v)))\nlet mt_next_rel_upd_even_pad #hsz #f n mt nmt i v = ()\n#pop-options\n\nval mt_next_rel_upd_odd:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n n:pos ->\n mt:merkle_tree #hsz n ->\n nmt:merkle_tree (n - 1) ->\n i:nat{i < pow2 (n-1)} ->\n v:padded_hash ->\n Lemma (requires mt_next_rel #_ #f n mt nmt)\n (ensures mt_next_rel #_ #f n\n (S.upd mt (2 * i + 1) v)\n (S.upd nmt i (padded_hash_fun #_ f (S.index mt (2 * i)) v)))\nlet mt_next_rel_upd_odd #hsz #f n mt nmt i v = ()\n\n// fournet: just [root]?\nval mt_get_root:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n #n:nat -> mt:merkle_tree #hsz n -> GTot (padded_hash #hsz)\nlet rec mt_get_root #hsz #f #n mt =\n if n = 0 then mt.[0]\n else mt_get_root #_ #f (mt_next_lv #_ #f mt)\n\n#push-options \"--initial_fuel 2 --max_fuel 2\"\n\nval mt_get_root_step: #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos -> mt:merkle_tree #hsz n ->\n Lemma (mt_get_root #_ #f mt ==\n padded_hash_fun #_ f (mt_get_root #_ #f (mt_left mt)) (mt_get_root #_ #f (mt_right mt)))\nlet rec mt_get_root_step #hsz #f #n mt =\n if n = 1 then ()\n else begin\n mt_get_root_step #_ #f (mt_next_lv #_ #f mt);\n mt_next_lv_mt_left #_ #f mt;\n mt_next_lv_mt_right #_ #f mt\n end\n\n#pop-options\n\ntype path #hsz n = S.lseq (padded_hash #hsz) n\n\n/// We first specify full paths, including padding.\n\nval mt_get_path:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->\n mt:merkle_tree #hsz n -> i:nat{i < pow2 n} -> GTot (path #hsz n)\nlet rec mt_get_path #hsz #f #n t i =\n if n = 0 then S.empty\n else S.cons\n (if i % 2 = 0 then t.[i + 1] else t.[i - 1])\n (mt_get_path #_ #f (mt_next_lv #_ #f t) (i / 2))\n\nval mt_verify_:\n #hsz:pos -> #f:hash_fun_t #hsz ->#n:nat ->\n p:path #hsz n -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> GTot (padded_hash #hsz)\nlet rec mt_verify_ #hsz #f #n p idx h =\n if n = 0 then h\n else mt_verify_ #_ #f #(n-1) (S.tail p) (idx / 2)\n (if idx % 2 = 0\n then padded_hash_fun #_ f h (S.head p)\n else padded_hash_fun #_ f (S.head p) h)\n\nval mt_verify:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->\n p:(path #hsz n) -> idx:nat{idx < pow2 n} -> padded_hash #hsz -> padded_hash #hsz -> GTot prop\nlet mt_verify #hsz #f #n p idx h rt =\n rt == mt_verify_ #_ #f p idx h\n\n\n/// Correctness: the root of a tree is correctly recomputed from any of its paths\n\nval hs_next_lv_get:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos ->\n hs:hashes{S.length hs = 2 * n} -> idx:nat{idx < 2 * n} ->\n Lemma ((hs_next_lv #_ #f #n hs).[idx / 2] ==\n (if idx % 2 = 0\n then padded_hash_fun #_ f hs.[idx] hs.[idx + 1]\n else padded_hash_fun #_ f hs.[idx - 1] hs.[idx]))\nlet rec hs_next_lv_get #hsz #f #n hs idx =\n if idx < 2 then ()\n else hs_next_lv_get #_ #f #(n-1) (S.slice hs 2 (S.length hs)) (idx - 2)\n\nval mt_next_lv_get:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:pos ->\n mt:merkle_tree #hsz n -> idx:nat{idx < pow2 n} ->\n Lemma (\n (mt_next_lv #_ #f mt).[idx / 2] ==\n (if idx % 2 = 0\n then padded_hash_fun #_ f mt.[idx] mt.[idx + 1]\n else padded_hash_fun #_ f mt.[idx - 1] mt.[idx]))\nlet mt_next_lv_get #hsz #f #n mt idx =\n hs_next_lv_get #_ #f #(pow2 (n-1)) mt idx\n\nval mt_get_path_ok_:\n #hsz:pos -> #f:hash_fun_t #hsz -> #n:nat ->\n t:merkle_tree #hsz n -> i:nat{i < pow2 n} ->\n Lemma (mt_verify_ #_ #f (mt_get_path #_ #f t i) i (mt_get t i) == mt_get_root #_ #f t)\nlet rec mt_get_path_ok_ #hsz #f #n mt idx =\n if n = 0 then ()\n else begin\n assert (S.head (mt_get_path #_ #f mt idx) ==\n (if idx % 2 = 0 then mt.[idx + 1] else mt.[idx - 1]));\n assert (S.equal (S.tail (mt_get_path #_ #f mt idx))\n (mt_get_path #_ #f (mt_next_lv #_ #f mt) (idx / 2)));\n mt_get_path_ok_ #_ #f (mt_next_lv #_ #f mt) (idx / 2);\n mt_next_lv_get #_ #f mt idx\n end\n\n\n/// Security: we reduce tree collisions to collisions on the hash\n/// compression function. Such collisions yield collisions on the SHA2\n/// standard (by adding the same length and padding to the\n/// accumulators).\n///\n/// One complication addressed in the proof is the handling of\n/// implicit padding.\n\n/// All hashes in a sequence are raw hashes, not padding\nval raw_hashes:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n hs:hashes #hsz -> Tot Type0 (decreases (S.length hs))\nlet rec raw_hashes #hsz #f hs =\n if S.length hs = 0 then True\n else (HRaw? (S.head hs) /\\ raw_hashes #_ #f (S.tail hs))\n\nval raw_hashes_raws:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n hs:hashes{raw_hashes #hsz #f hs} ->\n Tot (S.seq (hash #hsz)) (decreases (S.length hs))\nlet rec raw_hashes_raws #hsz #f hs =\n if S.length hs = 0 then S.empty\n else S.cons (HRaw?.hr (S.head hs)) (raw_hashes_raws #_ #f (S.tail hs))\n\nval raw_hashes_index:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n hs:hashes -> i:nat{i < S.length hs} ->\n Lemma (requires raw_hashes #_ #f hs)\n (ensures HRaw? #hsz hs.[i])\n (decreases i)\nlet rec raw_hashes_index #hsz #f hs i =\n if i = 0 then ()\n else raw_hashes_index #_ #f (S.tail hs) (i - 1)\n\nval raw_hashes_slice:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n hs:hashes -> i:nat -> j:nat{i <= j && j <= S.length hs} ->\n Lemma (requires raw_hashes #_ #f hs)\n (ensures raw_hashes #_ #f (S.slice hs i j))\n (decreases (j - i))\nlet rec raw_hashes_slice #hsz #f hs i j =\n if i = j then ()\n else (\n raw_hashes_index #_ #f hs i;\n raw_hashes_slice #_ #f hs (i + 1) j)\n\n/// All hashes in a sequence are just padding\nval pad_hashes:\n #hsz:pos -> #f:hash_fun_t #hsz ->\n\nPartial implementation:\nlet pad_hashes #hsz #f hs =\n \n"
},
{
"role": "assistant",
"content": "S.equal hs (S.create (S.length hs) HPad)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: x: s -> GradedMonad.st s GradedMonad.monoid_nat_plus 1 Prims.unit\nEffect: Prims.Tot\n\nContext:\nmodule GradedMonad\n\n(* NB: this is the old version of the graded monad that has a monoid\nindex parameter everywhere instead of a constraint on the type. We\nkeep it for CI purposes. See doc/book/code/GradedMonad.fst for better\nversion. *)\n\n#set-options \"--warn_error -350\"\n\n//SNIPPET_START:monoid$\nclass monoid (a:Type) =\n{\n op : a -> a -> a;\n one : a;\n properties: squash (\n (forall (x:a). op one x == x /\\ op x one == x) /\\\n (forall (x y z:a). op x (op y z) == op (op x y) z)\n );\n}\n\ninstance monoid_nat_plus : monoid nat =\n{\n op = (fun (x y:nat) -> x + y);\n one = 0;\n properties = ()\n}\n//SNIPPET_END: monoid$\n\nclass graded_monad (#index:Type)\n (m: monoid index -> index -> Type -> Type) = \n{\n return : #a:Type -> #im:monoid index -> x:a -> m im one a;\n \n bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index ->\n m im ia a -> \n (a -> m im ib b) ->\n m im (op ia ib) b\n\n}\n//we now have do notation for graded monads\n\n\nlet st (s:Type) monoid_nat_plus (count:nat) (a:Type) = s -> a & s\ninstance st_graded (s:Type) : graded_monad (st s) =\n{ \n return = (fun #a #im (x:a) s -> x, s);\n bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s)\n}\n\n// A write-counting grade monad\n\nPartial implementation:\nlet put #s (x: s) : st s monoid_nat_plus 1 unit =\n \n"
},
{
"role": "assistant",
"content": "fun _ -> (), x"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: s: Type -> GradedMonad.graded_monad (GradedMonad.st s)\nEffect: Prims.Tot\n\nContext:\nmodule GradedMonad\n\n(* NB: this is the old version of the graded monad that has a monoid\nindex parameter everywhere instead of a constraint on the type. We\nkeep it for CI purposes. See doc/book/code/GradedMonad.fst for better\nversion. *)\n\n#set-options \"--warn_error -350\"\n\n//SNIPPET_START:monoid$\nclass monoid (a:Type) =\n{\n op : a -> a -> a;\n one : a;\n properties: squash (\n (forall (x:a). op one x == x /\\ op x one == x) /\\\n (forall (x y z:a). op x (op y z) == op (op x y) z)\n );\n}\n\ninstance monoid_nat_plus : monoid nat =\n{\n op = (fun (x y:nat) -> x + y);\n one = 0;\n properties = ()\n}\n//SNIPPET_END: monoid$\n\nclass graded_monad (#index:Type)\n (m: monoid index -> index -> Type -> Type) = \n{\n return : #a:Type -> #im:monoid index -> x:a -> m im one a;\n \n bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index ->\n m im ia a -> \n (a -> m im ib b) ->\n m im (op ia ib) b\n\n}\n//we now have do notation for graded monads\n\nPartial implementation:\n[@@ FStar.Tactics.Typeclasses.tcinstance]\nlet st_graded (s: Type) : graded_monad (st s) =\n \n"
},
{
"role": "assistant",
"content": "{\n return = (fun #a #im (x: a) s -> x, s);\n bind\n =\n (fun #a #b #ia #ib #im f g s ->\n let x, s = f s in\n g x s)\n}"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: s: Type -> monoid_nat_plus: _ -> count: Prims.nat -> a: Type -> Type\nEffect: Prims.Tot\n\nContext:\nmodule GradedMonad\n\n(* NB: this is the old version of the graded monad that has a monoid\nindex parameter everywhere instead of a constraint on the type. We\nkeep it for CI purposes. See doc/book/code/GradedMonad.fst for better\nversion. *)\n\n#set-options \"--warn_error -350\"\n\n//SNIPPET_START:monoid$\nclass monoid (a:Type) =\n{\n op : a -> a -> a;\n one : a;\n properties: squash (\n (forall (x:a). op one x == x /\\ op x one == x) /\\\n (forall (x y z:a). op x (op y z) == op (op x y) z)\n );\n}\n\ninstance monoid_nat_plus : monoid nat =\n{\n op = (fun (x y:nat) -> x + y);\n one = 0;\n properties = ()\n}\n//SNIPPET_END: monoid$\n\nclass graded_monad (#index:Type)\n (m: monoid index -> index -> Type -> Type) = \n{\n return : #a:Type -> #im:monoid index -> x:a -> m im one a;\n \n bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index ->\n m im ia a -> \n (a -> m im ib b) ->\n m im (op ia ib) b\n\n}\n//we now have do notation for graded monads\n\nPartial implementation:\nlet st (s: Type) monoid_nat_plus (count: nat) (a: Type) =\n \n"
},
{
"role": "assistant",
"content": "s -> a & s"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: GradedMonad.st s GradedMonad.monoid_nat_plus (GradedMonad.op 0 1) Prims.unit\nEffect: Prims.Tot\n\nContext:\nmodule GradedMonad\n\n(* NB: this is the old version of the graded monad that has a monoid\nindex parameter everywhere instead of a constraint on the type. We\nkeep it for CI purposes. See doc/book/code/GradedMonad.fst for better\nversion. *)\n\n#set-options \"--warn_error -350\"\n\n//SNIPPET_START:monoid$\nclass monoid (a:Type) =\n{\n op : a -> a -> a;\n one : a;\n properties: squash (\n (forall (x:a). op one x == x /\\ op x one == x) /\\\n (forall (x y z:a). op x (op y z) == op (op x y) z)\n );\n}\n\ninstance monoid_nat_plus : monoid nat =\n{\n op = (fun (x y:nat) -> x + y);\n one = 0;\n properties = ()\n}\n//SNIPPET_END: monoid$\n\nclass graded_monad (#index:Type)\n (m: monoid index -> index -> Type -> Type) = \n{\n return : #a:Type -> #im:monoid index -> x:a -> m im one a;\n \n bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index ->\n m im ia a -> \n (a -> m im ib b) ->\n m im (op ia ib) b\n\n}\n//we now have do notation for graded monads\n\n\nlet st (s:Type) monoid_nat_plus (count:nat) (a:Type) = s -> a & s\ninstance st_graded (s:Type) : graded_monad (st s) =\n{ \n return = (fun #a #im (x:a) s -> x, s);\n bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s)\n}\n\n// A write-counting grade monad\nlet get #s : st s monoid_nat_plus 0 s = fun s -> s, s\nlet put #s (x:s) : st s monoid_nat_plus 1 unit = fun _ -> (), x\n\nPartial implementation:\nlet test #s =\n \n"
},
{
"role": "assistant",
"content": "x <-- get #s ;\nput x"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: GradedMonad.st s GradedMonad.monoid_nat_plus 0 s\nEffect: Prims.Tot\n\nContext:\nmodule GradedMonad\n\n(* NB: this is the old version of the graded monad that has a monoid\nindex parameter everywhere instead of a constraint on the type. We\nkeep it for CI purposes. See doc/book/code/GradedMonad.fst for better\nversion. *)\n\n#set-options \"--warn_error -350\"\n\n//SNIPPET_START:monoid$\nclass monoid (a:Type) =\n{\n op : a -> a -> a;\n one : a;\n properties: squash (\n (forall (x:a). op one x == x /\\ op x one == x) /\\\n (forall (x y z:a). op x (op y z) == op (op x y) z)\n );\n}\n\ninstance monoid_nat_plus : monoid nat =\n{\n op = (fun (x y:nat) -> x + y);\n one = 0;\n properties = ()\n}\n//SNIPPET_END: monoid$\n\nclass graded_monad (#index:Type)\n (m: monoid index -> index -> Type -> Type) = \n{\n return : #a:Type -> #im:monoid index -> x:a -> m im one a;\n \n bind : #a:Type -> #b:Type -> #ia:index -> #ib:index -> #im:monoid index ->\n m im ia a -> \n (a -> m im ib b) ->\n m im (op ia ib) b\n\n}\n//we now have do notation for graded monads\n\n\nlet st (s:Type) monoid_nat_plus (count:nat) (a:Type) = s -> a & s\ninstance st_graded (s:Type) : graded_monad (st s) =\n{ \n return = (fun #a #im (x:a) s -> x, s);\n bind = (fun #a #b #ia #ib #im f g s -> let x, s = f s in g x s)\n}\n\nPartial implementation:\nlet get #s : st s monoid_nat_plus 0 s =\n \n"
},
{
"role": "assistant",
"content": "fun s -> s, s"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: f: MerkleTree.Spec.hash_fun_t -> lh: MerkleTree.Spec.padded_hash -> rh: MerkleTree.Spec.padded_hash\n -> Prims.GTot MerkleTree.Spec.padded_hash\nEffect: Prims.GTot\n\nContext:\nmodule MerkleTree.Spec\n\nopen FStar.Classical\nopen FStar.Mul\nopen FStar.Seq\n\nmodule S = FStar.Seq\n\n#set-options \"--max_fuel 0 --max_ifuel 0 --z3rlimit 10\"\n\n// For SHA2_256, this is is a sequence of 32 bytes\n// These are secret bytes, hence not an eqtype\ntype hash (#hsz:pos) = b:Spec.Hash.Definitions.bytes { Seq.length b = hsz }\n\ntype hash_fun_t (#hsz:pos) = hash #hsz -> hash #hsz -> GTot (hash #hsz)\n\nval sha256_compress: hash_fun_t #32\nlet sha256_compress src1 src2 =\n let sz = Spec.Hash.Definitions.SHA2_256 in\n let hash_alg = Spec.Hash.Definitions.SHA2_256 in\n let acc = Spec.Agile.Hash.init hash_alg in\n let acc = Spec.Agile.Hash.update hash_alg acc (S.append src1 src2) in\n Spec.Agile.Hash.finish hash_alg acc ()\n\n/// For simplicity, we will specify the root for a sequence of [i]\n/// tags where [i <= 2^n] as the root of a full binary tree with [2^n]\n/// leaves obtained by padding the sequence with dummies. This\n/// requires extending the definitions of hashes and hash functions. Our\n/// extended definition of hash justifies skipping any concrete\n/// computation on dummies.\nnoeq\ntype padded_hash #hsz =\n| HRaw: hr:hash #hsz -> padded_hash #hsz\n| HPad // right padding to make the size of a Merkle tree a power of 2\n\nPartial implementation:\nlet padded_hash_fun #hsz f lh rh =\n \n"
},
{
"role": "assistant",
"content": "allow_inversion (padded_hash #hsz);\nmatch lh, rh with\n| HPad, _ -> HPad\n| _, HPad -> lh\n| HRaw lhr, HRaw rhr -> HRaw (f lhr rhr)"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n ws: Hacl.Spec.SHA2.Vec.ws_spec a m ->\n j: Prims.nat{j < Hacl.Spec.SHA2.Vec.lanes a m} ->\n i: Prims.nat{i < 16}\n -> FStar.Pervasives.Lemma\n (ensures\n (let l = Hacl.Spec.SHA2.Vec.lanes a m in\n (Hacl.Spec.SHA2.Vec.ws_spec_v (Hacl.Spec.SHA2.Vec.transpose_ws ws)).[ j ].[ i ] ==\n (Lib.IntVector.vec_v ws.[ (i / l) * l + j ]).[ i % l ]))\nEffect: FStar.Pervasives.Lemma\n\nContext:\nmodule Hacl.Spec.SHA2.Lemmas\n\nopen FStar.Mul\nopen Lib.IntTypes\nopen Lib.Sequence\nopen Lib.IntVector\nopen Lib.IntVector.Transpose\n\nopen Spec.Hash.Definitions\nopen Hacl.Spec.SHA2.Vec\n\n\n#set-options \"--z3rlimit 50 --fuel 0 --ifuel 1\"\n\nval transpose_ws4_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 4} // lanes a m * lanes a m = 16\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n (vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws4_lemma_ij #a #m ws j i =\n let l = lanes a m in\n let i_sub = i / l in\n let j_sub = i % l in\n assert (i_sub * l + j_sub == i);\n\n let vs = sub ws (i_sub * l) l in\n eq_intro (sub (transpose_ws4 ws) (i_sub * l) l) (transpose4x4_lseq vs);\n //assert ((transpose_ws4 ws).[i] == (sub (transpose_ws4 ws) (i_sub * l) l).[j_sub]);\n //assert ((transpose_ws4 ws).[i] == (transpose4x4_lseq vs).[j_sub]);\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v (transpose4x4_lseq vs).[j_sub]).[j]);\n transpose4x4_lemma vs;\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v vs.[j]).[j_sub]);\n assert ((vec_v (transpose_ws4 ws).[i]).[j] == (vec_v ws.[i_sub * l + j]).[j_sub])\n\n\nval transpose_ws8_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{lanes a m == 8}\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n (vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i / l * l + j]).[i % l])\n\nlet transpose_ws8_lemma_ij #a #m ws j i =\n let l = lanes a m in\n let i_sub = i / l in\n let j_sub = i % l in\n assert (i_sub * l + j_sub == i);\n\n let vs = sub ws (i_sub * l) l in\n eq_intro (sub (transpose_ws8 ws) (i_sub * l) l) (transpose8x8_lseq vs);\n assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v (transpose8x8_lseq vs).[j_sub]).[j]);\n transpose8x8_lemma vs;\n assert ((vec_v (transpose_ws8 ws).[i]).[j] == (vec_v ws.[i_sub * lanes a m + j]).[j_sub])\n\n\nval transpose_ws_lemma_ij:\n #a:sha2_alg\n -> #m:m_spec{is_supported a m}\n -> ws:ws_spec a m\n -> j:nat{j < lanes a m}\n -> i:nat{i < 16} ->\n Lemma\n (let l = lanes a m in\n ((ws_spec_v (transpose_ws ws)).[j]).[i] == (vec_v ws.[i / l * l + j]).[i % l])\n\nPartial implementation:\nlet transpose_ws_lemma_ij #a #m ws j i =\n \n"
},
{
"role": "assistant",
"content": "assert (((ws_spec_v (transpose_ws ws)).[ j ]).[ i ] == (vec_v (transpose_ws ws).[ i ]).[ j ]);\nmatch lanes a m with\n| 1 -> ()\n| 4 -> transpose_ws4_lemma_ij #a #m ws j i\n| 8 -> transpose_ws8_lemma_ij #a #m ws j i"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n problem: FStar.Tactics.PatternMatching.matching_problem ->\n hypotheses: Prims.list FStar.Tactics.PatternMatching.hypothesis ->\n goal: FStar.Tactics.NamedView.term ->\n body: (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a)\n -> FStar.Tactics.Effect.Tac a\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\n\nPartial implementation:\nlet solve_mp\n #a\n (problem: matching_problem)\n (hypotheses: list hypothesis)\n (goal: term)\n (body: (matching_solution -> Tac a))\n : Tac a =\n \n"
},
{
"role": "assistant",
"content": "let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] }\nin\nsolve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n key: FStar.Tactics.PatternMatching.varname ->\n ls: Prims.list (FStar.Tactics.PatternMatching.varname * b)\n -> FStar.Tactics.Effect.Tac b\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\nPartial implementation:\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b)) : Tac b =\n \n"
},
{
"role": "assistant",
"content": "match List.Tot.Base.assoc key ls with\n| None -> fail (\"Not found: \" ^ key)\n| Some x -> x"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: binder_kind: FStar.Tactics.PatternMatching.abspat_binder_kind -> FStar.Stubs.Reflection.Types.term\nEffect: Prims.Tot\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\nsucceed. **)\nlet rec solve_mp_for_hyps #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (partial_solution: matching_solution)\n : Tac a =\n match mp_hyps with\n | [] -> body partial_solution\n | (name, pat) :: pats ->\n solve_mp_for_single_hyp name pat hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution\n\n(** Solve a matching problem.\n\nThe solution returned is constructed to ensure that the continuation ``body``\nsucceeds: this implements the usual backtracking-match semantics. **)\nlet solve_mp #a (problem: matching_problem)\n (hypotheses: list hypothesis) (goal: term)\n (body: matching_solution -> Tac a)\n : Tac a =\n let goal_ps =\n match problem.mp_goal with\n | None -> { ms_vars = []; ms_hyps = [] }\n | Some pat ->\n match interp_pattern pat goal with\n | Failure ex -> fail (\"Failed to match goal: \" ^ (string_of_match_exception ex))\n | Success bindings -> { ms_vars = bindings; ms_hyps = [] } in\n solve_mp_for_hyps #a problem.mp_hyps hypotheses body goal_ps\n\n/// A DSL for pattern-matching\n/// ==========================\n///\n/// Using pattern-matching problems as defined above is relatively cumbersome,\n/// so we now introduce a lightweight notation, in two steps: pattern notations,\n/// and matching-problem notations.\n///\n/// Pattern notations\n/// -----------------\n///\n/// The first part of our pattern-matching syntax is pattern notations: we\n/// provide a reflective function which constructs a pattern from a term:\n/// variables are holes, free variables are constants, and applications are\n/// application patterns.\n\n(* FIXME: MOVE *)\nlet name_of_namedv (x:namedv) : Tac string =\n unseal (inspect_namedv x).ppname\n\n(** Compile a term `tm` into a pattern. **)\nlet rec pattern_of_term_ex tm : Tac (match_res pattern) =\n match inspect tm with\n | Tv_Var bv ->\n return (PVar (name_of_namedv bv))\n | Tv_FVar fv\n | Tv_UInst fv _ ->\n let qn = fv_to_string fv in\n return (PQn qn)\n | Tv_Type _ ->\n return PType\n | Tv_App f (x, _) ->\n let? fpat = pattern_of_term_ex f in\n let? xpat = pattern_of_term_ex x in\n return (PApp fpat xpat)\n | _ -> raise (UnsupportedTermInPattern tm)\n\n(** β-reduce a term `tm`.\nThis is useful to remove needles function applications introduced by F*, like\n``(fun a b c -> a) 1 2 3``. **)\nlet beta_reduce (tm: term) : Tac term =\n norm_term [] tm\n\n(** Compile a term `tm` into a pattern. **)\nlet pattern_of_term tm : Tac pattern =\n match pattern_of_term_ex tm with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Problem notations\n/// -----------------\n///\n/// We then introduce a DSL for matching problems, best explained on the\n/// following example::\n///\n/// (fun (a b c: ①) (h1 h2 h3: hyp ②) (g: pm_goal ③) → ④)\n///\n/// This notation is intended to express a pattern-matching problems with three\n/// holes ``a``, ``b``, and ``c`` of type ①, matching hypotheses ``h1``, ``h2``,\n/// and ``h3`` against pattern ② and the goal against the pattern ③. The body\n/// of the notation (④) is then run with appropriate terms bound to ``a``,\n/// ``b``, and ``c``, appropriate binders bound to ``h1``, ``h2``, and ``h3``,\n/// and ``()`` bound to ``g``.\n///\n/// We call these patterns ``abspat``s (abstraction patterns), and we provide\n/// facilities to parse them into matching problems, and to run their bodies\n/// against a particular matching solution.\n\n// We used to annotate variables with an explicit 'var' marker, but then that\n// var annotation leaked into the types of other hypotheses due to type\n// inference, requiring non-trivial normalization.\n\n// let var (a: Type) = a\nlet hyp (a: Type) = binding\nlet pm_goal (a: Type) = unit\n\nlet hyp_qn = `%hyp\nlet goal_qn = `%pm_goal\n\nnoeq type abspat_binder_kind =\n| ABKVar of typ\n| ABKHyp\n| ABKGoal\n\nlet string_of_abspat_binder_kind = function\n | ABKVar _ -> \"varname\"\n | ABKHyp -> \"hyp\"\n | ABKGoal -> \"goal\"\n\nnoeq type abspat_argspec =\n { asa_name: absvar;\n asa_kind: abspat_binder_kind }\n\n// We must store this continuation, because recomputing it yields different\n// names when the binders are re-opened.\ntype abspat_continuation =\n list abspat_argspec * term\n\nlet type_of_named_binder (nb : binder) : term =\n nb.sort\n\nlet classify_abspat_binder (b : binder): Tac (abspat_binder_kind * term) =\n let varname = \"v\" in\n let hyp_pat = PApp (PQn hyp_qn) (PVar varname) in\n let goal_pat = PApp (PQn goal_qn) (PVar varname) in\n\n let typ = type_of_named_binder b in\n match interp_pattern hyp_pat typ with\n | Success [(_, hyp_typ)] -> ABKHyp, hyp_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (1)\"\n | Failure _ ->\n match interp_pattern goal_pat typ with\n | Success [(_, goal_typ)] -> ABKGoal, goal_typ\n | Success _ -> fail \"classifiy_abspat_binder: impossible (2)\"\n | Failure _ -> ABKVar typ, typ\n\n(** Split an abstraction `tm` into a list of binders and a body. **)\nlet rec binders_and_body_of_abs tm : Tac (list binder * term) =\n match inspect tm with\n | Tv_Abs binder tm ->\n let binders, body = binders_and_body_of_abs tm in\n binder :: binders, body\n | _ -> [], tm\n\nlet cleanup_abspat (t: term) : Tac term =\n norm_term [] t\n\n\nlet name_of_named_binder (nb : binder) : Tac string =\n unseal nb.ppname\n\n(** Parse a notation into a matching problem and a continuation.\n\nPattern-matching notations are of the form ``(fun binders… -> continuation)``,\nwhere ``binders`` are of one of the forms ``var …``, ``hyp …``, or ``goal …``.\n``var`` binders are typed holes to be used in other binders; ``hyp`` binders\nindicate a pattern to be matched against hypotheses; and ``goal`` binders match\nthe goal.\n\n\nA reduction phase is run to ensure that the pattern looks reasonable; it is\nneeded because F* tends to infer arguments in β-expanded form.\n\nThe continuation returned can't directly be applied to a pattern-matching\nsolution; see ``interp_abspat_continuation`` below for that. **)\nlet matching_problem_of_abs (tm: term)\n : Tac (matching_problem * abspat_continuation) =\n\n let binders, body = binders_and_body_of_abs (cleanup_abspat tm) in\n debug (\"Got binders: \" ^ (String.concat \", \"\n (map (fun b -> name_of_named_binder b <: Tac string) binders)));\n\n let classified_binders : list (binder & string & abspat_binder_kind & typ) =\n map (fun binder ->\n let bv_name = name_of_named_binder binder in\n debug (\"Got binder: \" ^ bv_name ^ \"; type is \" ^\n term_to_string (type_of_named_binder binder));\n let binder_kind, typ = classify_abspat_binder binder in\n (binder, bv_name, binder_kind, typ))\n binders in\n\n let problem =\n fold_left\n (fun problem (binder, bv_name, binder_kind, typ) ->\n debug (\"Compiling binder \" ^ name_of_named_binder binder ^\n \", classified as \" ^ string_of_abspat_binder_kind binder_kind ^\n \", with type \" ^ term_to_string typ);\n match binder_kind with\n | ABKVar _ -> { problem with mp_vars = bv_name :: problem.mp_vars }\n | ABKHyp -> { problem with mp_hyps = (bv_name, (pattern_of_term typ))\n :: problem.mp_hyps }\n | ABKGoal -> { problem with mp_goal = Some (pattern_of_term typ) })\n ({ mp_vars = []; mp_hyps = []; mp_goal = None })\n classified_binders in\n\n let continuation =\n let abspat_argspec_of_binder xx : Tac abspat_argspec =\n match xx with | (binder, xx, binder_kind, yy) ->\n { asa_name = binder_to_binding binder; asa_kind = binder_kind } in\n (map abspat_argspec_of_binder classified_binders, tm) in\n\n let mp =\n { mp_vars = List.Tot.Base.rev #varname problem.mp_vars;\n mp_hyps = List.Tot.Base.rev #(varname * pattern) problem.mp_hyps;\n mp_goal = problem.mp_goal } in\n\n debug (\"Got matching problem: \" ^ (string_of_matching_problem mp));\n mp, continuation\n\n/// Continuations\n/// -------------\n///\n/// Parsing an abspat yields a matching problem and a continuation of type\n/// ``abspat_continuation``, which is essentially just a list of binders and a\n/// term (the body of the abstraction pattern).\n\n(** Get the (quoted) type expected by a specific kind of abspat binder. **)\nlet arg_type_of_binder_kind binder_kind : Tac term =\n match binder_kind with\n | ABKVar typ -> typ\n | ABKHyp -> `binder\n | ABKGoal -> `unit\n\nPartial implementation:\nlet locate_fn_of_binder_kind binder_kind =\n \n"
},
{
"role": "assistant",
"content": "match binder_kind with\n| ABKVar _ -> `ms_locate_var\n| ABKHyp -> `ms_locate_hyp\n| ABKGoal -> `ms_locate_unit"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n mp_hyps:\n Prims.list (FStar.Tactics.PatternMatching.varname * FStar.Tactics.PatternMatching.pattern) ->\n hypotheses: Prims.list FStar.Tactics.PatternMatching.hypothesis ->\n body: (_: FStar.Tactics.PatternMatching.matching_solution -> FStar.Tactics.Effect.Tac a) ->\n partial_solution: FStar.Tactics.PatternMatching.matching_solution\n -> FStar.Tactics.Effect.Tac a\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\nthe pattern. Returns a result in the exception monad. **)\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm:term)\n : Tac (match_res bindings) =\n let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' -> if term_eq tm tm' then return cur_bindings\n else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings) in\n let interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm)) in\n let interp_app (p_hd p_arg: (p:pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm)) in\n match pat with\n | PVar var -> interp_var var cur_bindings tm\n | PQn qn -> interp_qn qn cur_bindings tm\n | PType -> interp_type cur_bindings tm\n | PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm\n\n(** Match a pattern `pat` against a term.\nReturns a result in the exception monad. **)\nlet interp_pattern (pat: pattern) : term -> Tac (match_res bindings) =\n fun (tm: term) ->\n let? rev_bindings = interp_pattern_aux pat [] tm in\n return (List.Tot.Base.rev rev_bindings)\n\n(** Match a term `tm` against a pattern `pat`.\nRaises an exception if the match fails. This is mostly useful for debugging:\nuse ``mgw`` to capture matches. **)\nlet match_term pat (tm : term) : Tac bindings =\n match interp_pattern pat (norm_term [] tm) with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern-matching problems\n/// =========================\n///\n/// Generalizing past single-term single-pattern problems, we obtain the\n/// following notions of pattern-matching problems and solutions:\n\nlet debug msg : Tac unit = () // print msg\n\n/// Definitions\n/// -----------\n\nlet absvar = binding\ntype hypothesis = binding\n\n/// A matching problem is composed of holes (``mp_vars``), hypothesis patterns\n/// (``mp_hyps``), and a goal pattern (``mp_goal``).\n\nnoeq type matching_problem =\n { mp_vars: list varname;\n mp_hyps: list (varname * pattern);\n mp_goal: option pattern }\n\nlet string_of_matching_problem mp =\n let vars =\n String.concat \", \" mp.mp_vars in\n let hyps =\n String.concat \"\\n \"\n (List.Tot.Base.map (fun (nm, pat) ->\n nm ^ \": \" ^ (string_of_pattern pat)) mp.mp_hyps) in\n let goal = match mp.mp_goal with\n | None -> \"_\"\n | Some pat -> string_of_pattern pat in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \"\\n\" ^\n \" goal: \" ^ goal ^ \" }\"\n\n/// A solution is composed of terms captured to mach the holes, and binders\n/// captured to match hypothesis patterns.\n\nnoeq type matching_solution =\n { ms_vars: list (varname * term);\n ms_hyps: list (varname * hypothesis) }\n\nlet string_of_matching_solution ms =\n let vars =\n String.concat \"\\n \"\n (map (fun (varname, tm) ->\n varname ^ \": \" ^ (term_to_string tm)) ms.ms_vars) in\n let hyps =\n String.concat \"\\n \"\n (map (fun (nm, binding) ->\n nm ^ \": \" ^ (binding_to_string binding)) ms.ms_hyps) in\n \"\\n{ vars: \" ^ vars ^ \"\\n\" ^\n \" hyps: \" ^ hyps ^ \" }\"\n\n(** Find a varname in an association list; fail if it can't be found. **)\nlet assoc_varname_fail (#b: Type) (key: varname) (ls: list (varname * b))\n : Tac b =\n match List.Tot.Base.assoc key ls with\n | None -> fail (\"Not found: \" ^ key)\n | Some x -> x\n\nlet ms_locate_hyp (a: Type) (solution: matching_solution)\n (name: varname) : Tac hypothesis =\n assoc_varname_fail name solution.ms_hyps\n\nlet ms_locate_var (a: Type) (solution: matching_solution)\n (name: varname) : Tac a =\n unquote #a (assoc_varname_fail name solution.ms_vars)\n\nlet ms_locate_unit (a: Type) _solution _binder_name : Tac unit =\n ()\n\n/// Resolution\n/// ----------\n///\n/// Solving a matching problem is a two-steps process: find an initial\n/// assignment for holes based on the goal pattern, then find a set of\n/// hypotheses matching hypothesis patterns.\n///\n/// Note that the implementation takes a continuation of type\n/// ``matching_solution -> Tac a``. This continuation is needed because we want\n/// users to be able to provide extra criteria on matching solutions (most\n/// commonly, this criterion is that a particular tactic should run\n/// successfuly).\n///\n/// This makes it easy to implement a simple for of search through the context,\n/// where one can find a hypothesis matching a particular predicate by\n/// constructing a trivial matching problem and passing the predicate as the\n/// continuation.\n\n(** Scan ``hypotheses`` for a match for ``pat`` that lets ``body`` succeed.\n\n``name`` is used to refer to the hypothesis matched in the final solution.\n``part_sol`` includes bindings gathered while matching previous solutions. **)\nlet rec solve_mp_for_single_hyp #a\n (name: varname)\n (pat: pattern)\n (hypotheses: list hypothesis)\n (body: matching_solution -> Tac a)\n (part_sol: matching_solution)\n : Tac a =\n match hypotheses with\n | [] ->\n fail #a \"No matching hypothesis\"\n | h :: hs ->\n or_else // Must be in ``Tac`` here to run `body`\n (fun () ->\n match interp_pattern_aux pat part_sol.ms_vars (type_of_binding h) with\n | Failure ex ->\n fail (\"Failed to match hyp: \" ^ (string_of_match_exception ex))\n | Success bindings ->\n let ms_hyps = (name, h) :: part_sol.ms_hyps in\n body ({ part_sol with ms_vars = bindings; ms_hyps = ms_hyps }))\n (fun () ->\n solve_mp_for_single_hyp name pat hs body part_sol)\n\n(** Scan ``hypotheses`` for matches for ``mp_hyps`` that lets ``body``\n\nPartial implementation:\nlet rec solve_mp_for_hyps\n #a\n (mp_hyps: list (varname * pattern))\n (hypotheses: list hypothesis)\n (body: (matching_solution -> Tac a))\n (partial_solution: matching_solution)\n : Tac a =\n \n"
},
{
"role": "assistant",
"content": "match mp_hyps with\n| [] -> body partial_solution\n| (name, pat) :: pats ->\n solve_mp_for_single_hyp name\n pat\n hypotheses\n (solve_mp_for_hyps pats hypotheses body)\n partial_solution"
}
] |
[
{
"role": "user",
"content": "Complete this F* function with a correct proof.\n\nType: \n pat: FStar.Tactics.PatternMatching.pattern ->\n cur_bindings: FStar.Tactics.PatternMatching.bindings ->\n tm: FStar.Tactics.NamedView.term\n -> FStar.Tactics.Effect.Tac\n (FStar.Tactics.PatternMatching.match_res FStar.Tactics.PatternMatching.bindings)\nEffect: FStar.Tactics.Effect.Tac\n\nContext:\n(*\n Copyright 2008-2018 Microsoft Research\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*)\n/// ==========================\n/// Pattern-matching tactics\n/// ==========================\n///\n/// :Author: Clément Pit-Claudel\n/// :Contact: clement.pitclaudel@live.com\n/// :Date: 2017-10-13\n\nmodule FStar.Tactics.PatternMatching\n\nopen FStar.Tactics.V2\n\n/// Contents\n/// ========\n///\n/// 1 Contents\n/// 2 Motivation\n/// 3 Some utility functions\n/// 4 Pattern types\n/// 5 Pattern matching exceptions\n/// 5.1 Types of exceptions\n/// 5.2 The exception monad\n/// 5.3 Liftings\n/// 6 Pattern interpretation\n/// 7 Pattern-matching problems\n/// 7.1 Definitions\n/// 7.2 Resolution\n/// 8 A DSL for pattern-matching\n/// 8.1 Pattern notations\n/// 8.2 Problem notations\n/// 8.3 Continuations\n/// 9 Putting it all together\n/// 10 Examples\n/// 10.1 Simple examples\n/// 10.2 A real-life example\n/// 11 Possible extensions\n/// 12 Notes\n///\n/// Motivation\n/// ==========\n///\n/// Suppose you have a goal of the form ``squash (a == b)``. How do you capture\n/// `a` and `b` for further inspection?\n///\n/// Here's a basic (but cumbersome!) implementation:\n\nlet fetch_eq_side () : Tac (term * term) =\n let g = cur_goal () in\n match inspect g with\n | Tv_App squash (g, _) ->\n (match inspect squash with\n | Tv_UInst squash _\n | Tv_FVar squash ->\n if fv_to_string squash = flatten_name squash_qn then\n (match inspect g with\n | Tv_App eq_type_x (y, _) ->\n (match inspect eq_type_x with\n | Tv_App eq_type (x, _) ->\n (match inspect eq_type with\n | Tv_App eq (typ, _) ->\n (match inspect eq with\n | Tv_UInst eq _\n | Tv_FVar eq ->\n if fv_to_string eq = flatten_name eq2_qn then\n (x, y)\n else fail \"not an equality\"\n | _ -> fail \"not an app2 of fvar: \")\n | _ -> fail \"not an app3\")\n | _ -> fail \"not an app2\")\n | _ -> fail \"not an app under squash\")\n else fail \"not a squash\"\n | _ -> fail \"not an app of fvar at top level\")\n | _ -> fail \"not an app at top level\"\n\n/// …and here's how you could use it:\n\n(* let _ = *)\n(* assert_by_tactic (1 + 1 == 2) *)\n(* (fun () -> let l, r = fetch_eq_side () in *)\n(* print (term_to_string l ^ \" / \" ^ term_to_string r)) *)\n\n/// This file defines pattern-matching primitives that let you write the same\n/// thing like this…\n///\n/// .. code:: fstar\n///\n/// let fetch_eq_side' #a () : Tac (term * term) =\n/// gpm (fun (left right: a) (g: pm_goal (squash (left == right))) ->\n/// (quote left, quote right) <: Tac (term * term))\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (fun () -> let l, r = fetch_eq_side' #int () in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r))\n///\n/// …or, more succinctly, like this:\n///\n/// .. code:: fstar\n///\n/// let _ =\n/// assert_by_tactic (1 + 1 == 2)\n/// (gpm (fun (left right: int) (g: pm_goal (squash (left == right))) ->\n/// let l, r = quote left, quote right in\n/// print (term_to_string l ^ \" / \" ^ term_to_string r) <: Tac unit))\n\n\n/// Some utility functions\n/// ======================\n///\n/// (Skip over this part on a quick read — these are just convenience functions)\n\n\n(** Ensure that tactic `t` fails. **)\nlet mustfail #a (t: unit -> Tac a) (message: string) : Tac unit =\n match trytac t with\n | Some _ -> fail message\n | None -> ()\n\n/// The following two tactics are needed because of issues with the ``Tac``\n/// effect.\n\nlet implies_intro' () : Tac unit =\n let _ = implies_intro () in ()\n\nlet repeat' #a (f: unit -> Tac a) : Tac unit =\n let _ = repeat f in ()\n\nlet and_elim' (h: binding) : Tac unit =\n and_elim (pack (Tv_Var h));\n clear h\n\n(** Use a hypothesis at type a to satisfy a goal at type squash a *)\nlet exact_hyp (a: Type0) (h: namedv) : Tac unit =\n let hd = quote (FStar.Squash.return_squash #a) in\n exact (mk_app hd [((pack (Tv_Var h)), Q_Explicit)])\n\n(** Use a hypothesis h (of type a) to satisfy a goal at type a *)\nlet exact_hyp' (h: namedv): Tac unit =\n exact (pack (Tv_Var h))\n\n/// Pattern types\n/// =============\n///\n/// Patterns are defined using a simple inductive type, mirroring the structure\n/// of ``term_view``.\n\ntype varname = string\n\ntype qn = string\n\ntype pattern =\n| PVar: name: varname -> pattern\n| PQn: qn: qn -> pattern\n| PType: pattern\n| PApp: hd: pattern -> arg: pattern -> pattern\n\nlet desc_of_pattern = function\n| PVar _ -> \"a variable\"\n| PQn qn -> \"a constant (\" ^ qn ^ \")\"\n| PType -> \"Type\"\n| PApp _ _ -> \"a function application\"\n\nlet rec string_of_pattern = function\n| PVar x -> \"?\" ^ x\n| PQn qn -> qn\n| PType -> \"Type\"\n| PApp l r -> \"(\" ^ string_of_pattern l ^ \" \"\n ^ string_of_pattern r ^ \")\"\n\n/// Pattern matching exceptions\n/// ===========================\n///\n/// Pattern-matching is defined as a pure, monadic function (because of issues\n/// with combining DM4F effects, but also because it helps with debugging).\n/// This section defines the exception monad.\n///\n/// Types of exceptions\n/// -------------------\n\nnoeq type match_exception =\n| NameMismatch of qn * qn\n| SimpleMismatch of pattern * term\n| NonLinearMismatch of varname * term * term\n| UnsupportedTermInPattern of term\n| IncorrectTypeInAbsPatBinder of typ\n\nlet term_head t : Tac string =\n match inspect t with\n | Tv_Var bv -> \"Tv_Var\"\n | Tv_BVar fv -> \"Tv_BVar\"\n | Tv_FVar fv -> \"Tv_FVar\"\n | Tv_UInst _ _ -> \"Tv_UInst\"\n | Tv_App f x -> \"Tv_App\"\n | Tv_Abs x t -> \"Tv_Abs\"\n | Tv_Arrow x t -> \"Tv_Arrow\"\n | Tv_Type _ -> \"Tv_Type\"\n | Tv_Refine x t -> \"Tv_Refine\"\n | Tv_Const cst -> \"Tv_Const\"\n | Tv_Uvar i t -> \"Tv_Uvar\"\n | Tv_Let r attrs b t1 t2 -> \"Tv_Let\"\n | Tv_Match t _ branches -> \"Tv_Match\"\n | Tv_AscribedT _ _ _ _ -> \"Tv_AscribedT\"\n | Tv_AscribedC _ _ _ _ -> \"Tv_AscribedC\"\n | Tv_Unknown -> \"Tv_Unknown\"\n | Tv_Unsupp -> \"Tv_Unsupp\"\n\nlet string_of_match_exception = function\n | NameMismatch (qn1, qn2) ->\n \"Match failure (name mismatch): expecting \" ^\n qn1 ^ \", found \" ^ qn2\n | SimpleMismatch (pat, tm) ->\n \"Match failure (sort mismatch): expecting \" ^\n desc_of_pattern pat ^ \", got \" ^ term_to_string tm\n | NonLinearMismatch (nm, t1, t2) ->\n \"Match failure (nonlinear mismatch): variable \" ^ nm ^\n \" needs to match both \" ^ (term_to_string t1) ^\n \" and \" ^ (term_to_string t2)\n | UnsupportedTermInPattern tm ->\n \"Match failure (unsupported term in pattern): \" ^\n term_to_string tm ^ \" (\" ^ term_head tm ^ \")\"\n | IncorrectTypeInAbsPatBinder typ ->\n \"Incorrect type in pattern-matching binder: \" ^\n term_to_string typ ^ \" (use one of ``var``, ``hyp …``, or ``goal …``)\"\n\n/// The exception monad\n/// -------------------\n\nnoeq type match_res a =\n| Success of a\n| Failure of match_exception\n\nlet return #a (x: a) : match_res a =\n Success x\n\nlet (let?) (#a #b: Type)\n (f: match_res a)\n (g: a -> Tac (match_res b))\n : Tac (match_res b) =\n match f with\n | Success aa -> g aa\n | Failure ex -> Failure ex\n\nlet raise #a (ex: match_exception) : match_res a =\n Failure ex\n\n/// Liftings\n/// --------\n///\n/// There's a natural lifting from the exception monad into the tactic effect:\n\nlet lift_exn_tac #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\nlet lift_exn_tactic #a #b (f: a -> match_res b) (aa: a) : Tac b =\n match f aa with\n | Success bb -> bb\n | Failure ex -> Tactics.fail (string_of_match_exception ex)\n\n/// Pattern interpretation\n/// ======================\n///\n/// This section implement pattern-matching. This is strictly a one term, one\n/// pattern implementation — handling cases in which mutliple hypotheses match\n/// the same pattern is done later.\n\ntype bindings = list (varname * term)\nlet string_of_bindings (bindings: bindings) =\n String.concat \"\\n\"\n (map (fun (nm, tm) -> (\">> \" ^ nm ^ \": \" ^ term_to_string tm))\n bindings)\n\n(** Match a pattern against a term.\n`cur_bindings` is a list of bindings collected while matching previous parts of\n\nPartial implementation:\nlet rec interp_pattern_aux (pat: pattern) (cur_bindings: bindings) (tm: term)\n : Tac (match_res bindings) =\n \n"
},
{
"role": "assistant",
"content": "let interp_var (v: varname) cur_bindings tm =\n match List.Tot.Base.assoc v cur_bindings with\n | Some tm' ->\n if term_eq tm tm' then return cur_bindings else raise (NonLinearMismatch (v, tm, tm'))\n | None -> return ((v, tm) :: cur_bindings)\nin\nlet interp_qn (qn: qn) cur_bindings tm =\n match inspect tm with\n | Tv_UInst fv _\n | Tv_FVar fv ->\n if fv_to_string fv = qn\n then return cur_bindings\n else raise (NameMismatch (qn, (fv_to_string fv)))\n | _ -> raise (SimpleMismatch (pat, tm))\nin\nlet interp_type cur_bindings tm =\n match inspect tm with\n | Tv_Type _ -> return cur_bindings\n | _ -> raise (SimpleMismatch (pat, tm))\nin\nlet interp_app (p_hd: (p: pattern{p << pat})) (p_arg: (p: pattern{p << pat})) cur_bindings tm =\n match inspect tm with\n | Tv_App hd (arg, _) ->\n let? with_hd = interp_pattern_aux p_hd cur_bindings hd in\n let? with_arg = interp_pattern_aux p_arg with_hd arg in\n return with_arg\n | _ -> raise (SimpleMismatch (pat, tm))\nin\nmatch pat with\n| PVar var -> interp_var var cur_bindings tm\n| PQn qn -> interp_qn qn cur_bindings tm\n| PType -> interp_type cur_bindings tm\n| PApp p_hd p_arg -> interp_app p_hd p_arg cur_bindings tm"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.